如何在Matlab

时间:2017-07-25 09:34:18

标签: matlab loops concatenation

我现在有一些代码在for循环中执行,但我最终会使用parfor。这就是为什么我需要分别保存每个循环的输出:

for Year = 2008:2016
  for PartOfYear = 1:12

  % some code that produces numerical values, vectors and strings

  end
end

我想分别保存每个循环的输出,最后将它们合并在一起,以便所有输出都是垂直连接的,从Year = 2008开始,PartOfYear = 1在第一行,然后Year = 2008,PartOfYear = 2,依此类推。我被困在如何编写这段代码 - 我查看了表格,单元格,eval和sprintf函数,但无法使其适用于我的情况。

2 个答案:

答案 0 :(得分:2)

你可以使用细胞(这就是我主要使用的) 看看代码

a=1; %some random const 

OParray=cell(1);
idx=1;colforYear=1;colforPart=2;colforA=3;

for Year = 2008:2016
for PartOfYear = 1:12
  str1='monday';
  a=a+1; %some random operation
  outPut=strcat(str1,num2str(a));
  OParray{idx,colforYear}=Year;
  OParray{idx,colforPart}=PartOfYear;
  OParray{idx,colforA}=outPut;
   idx=idx+1;
end
end

答案 1 :(得分:0)

避开eval,它使代码很难调试和解释,并且在matlab中建议不要使用任何一种方法创建动态变量作为良好实践。此外,始终从1向上开始索引,因为它只会让您的数据处理更轻松。

您最好创建一个结构并将每个输出保存为该结构中的值,该结构的索引值与for循环中的值相同。类似的东西:

Years= [2008:1:2016]

for Year = 1:length(Years)
    for PartofYear= 1:12

        Monthly_Out{PartofYear}= %whatever code generates your output

    end

    Yearly_Out{year}= vertcat(Monthly_Out{:,:});
end

Total_Output= vertcat{Yearly_Out{:,:});