Matlab-从嵌套循环存储数据 [英] Matlab - Storing data from a nested loop
问题描述
我想将双循环中的数据存储在矩阵(而不是单元格)中. 我尝试了以下代码(内部循环中使用的函数只是一个示例).
I would like to store the data from a double loop in a matrix (not a cell). I tried the following code (the function used in the inner loop here is just an example).
valuesforOPratio = zeros(41,1);
valuesforM = zeros(41,61);
NPVtotal=1;
for M = 40:100
for OPratio = 30:70;
NPVtotal = NPVtotal+1
valuesforOPratio(OPratio)=NPVtotal;
end
valuesforM(M) = valuesforOPratio
end
I get the following error:
In an assignment A(:) = B, the number of elements in A and B must be the same.
Error in sensitivity_opratio (line 10)
valuesforM(M) = valuesforOPratio
有关如何将数据存储在矩阵中的任何帮助?我想这很容易,但我没有到达那儿
Any help on how to store the data in a matrix ? I guess this is rather easy but I am not getting there
推荐答案
您的代码有一些问题:
1/您将valuesforOPratio
定义为41x1
向量.但是,在内部嵌套循环中,下标OPratio
从30变为70,这意味着当您编写valuesforOPratio(OPratio)=NPVtotal;
时,valuesforOPratio
向量的大小将增加到70.
1/ You define valuesforOPratio
as a 41x1
Vector. However, in the inner nested loop, the subscripts OPratio
go from 30 to 70, meaning when you write valuesforOPratio(OPratio)=NPVtotal;
the size of your valuesforOPratio
vector will increase to 70.
要纠正这一点,您可能要选择其中一个:
To rectify that, you might want to either :
- 使您的
OPratio
下标从1到41(即for OPratio=1:41 ...
) - 在上述通话中设置正确的下标(即
valuesforOPratio(OPratio-29)=NPVtotal;
)
- Make your
OPratio
subscript go from 1 to 41 (i.e.for OPratio=1:41 ...
) - Set the right subscript in the call mentionned above (i.e.
valuesforOPratio(OPratio-29)=NPVtotal;
)
2/当您编写valuesforM(M)=valuesforOPratio
时,您试图将向量(valuesforOPratio
)放在标量元素(valuesforM(M)
)中.
2/ When you write valuesforM(M)=valuesforOPratio
, you are trying to put a vector (valuesforOPratio
) in a scalar element (valuesforM(M)
).
要纠正这一点,您只需指定要用valuesforOPratio
中的值填充valuesforM
的整列,即:
To rectify that, you just need to specify that you want a whole column of valuesforM
to be filled with the values in valuesforOPratio
, i.e. :
valuesforM(:,M-39)=valuesforOPratio;
这篇关于Matlab-从嵌套循环存储数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!