MATLAB: Saving successive results

arrayfaq 4.6

Hi. I need some help with the problem below.
for k = 1:1:n;
sum = k^2+2k; % Just an example
end
At the end of the run, I wish to have a total of n variables named, say, array_1, array_2, … array_n. Each array should contain the value of the sum associated with the respective k. So, array_1 = 3, array 2 = 8, and so on.
I am having trouble renaming the variable. Any help?

Best Answer

Hi,
what you like to do can be done with eval:
n = 5;
for k = 1:1:n;
eval(['array_',num2str(k),'= k^2+2*k;']); % Just an example
end
But I would recommend avoid eval and use a Cell instead to capture the output:
n = 5;
array = cell(n,1);
for k = 1:1:n;
array{k} = k^2+2*k;
end
For some more details look under the following link for "How can I create variables A1, A2,...,A10 in a loop?"
Related Question