Matlab-从嵌套循环存储数据 [英] Matlab - Storing data from a nested loop

查看:437
本文介绍了Matlab-从嵌套循环存储数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将双循环中的数据存储在矩阵(而不是单元格)中. 我尝试了以下代码(内部循环中使用的函数只是一个示例).

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 :

  1. 使您的OPratio下标从1到41(即for OPratio=1:41 ...)
  2. 在上述通话中设置正确的下标(即valuesforOPratio(OPratio-29)=NPVtotal;)
  1. Make your OPratio subscript go from 1 to 41 (i.e. for OPratio=1:41 ...)
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆