Reputation: 323
I have some code that is executed in a for loop at the moment, but I will eventually use parfor. That is why I need to save the output for each loop separately:
for Year = 2008:2016
for PartOfYear = 1:12
% some code that produces numerical values, vectors and strings
end
end
I want to save the outputs for each loop separately and in the end merge it together, so that all the outputs are vertically concatenated, starting with Year=2008, PartOfYear = 1 in the first row, then Year = 2008, PartOfYear = 2, and so on. I am stuck as how to write this code - I looked into tables, cells, the eval and the sprintf function but couldn't make it work for my case.
Upvotes: 0
Views: 76
Reputation: 136
you can use cell (thats what i use mostly) check out the code
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
Upvotes: 2
Reputation: 33
Steer clear of eval, it makes code very difficult to debug and interpret, and either way creating dynamic variables isnt recommended in matlab as good practice. Also, always index starting from 1 going upwards because it just makes your life easier in data handling.
You're best off creating a structure and saving each output as a value in that structure that is indexed with the same value as the one in your for loop. Something like:
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{:,:});
Upvotes: 0