2017-07-25 41 views
0

我有一些代碼是在for循環中執行的,但我最終會使用parfor。這就是爲什麼我需要保存爲單獨每個迴路輸出:如何在Matlab中分別合併for循環中生成的輸出

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函數,但無法使其適用於我的案例。

+0

看看https://stackoverflow.com/documentation/matlab/4378/multithreading#t=20170725094117323641的第二部分。 –

+0

[在Matlab中創建並連接改變名稱的單元格的循環的可能的副本](https://stackoverflow.com/questions/45187964/create-and-concatenate-cells-that-c​​hange-name-in-every- for-loop-in-matlab) –

回答

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

+0

是的,類似的東西,但是,我也有字符串作爲輸出 - 這意味着我必須使用結構?還是細胞?我沒有任何經驗。 – LenaH

+0

@LenaH檢出修改後的代碼 – smriti

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{:,:});