# store for loop outcomes in matrix

3 views (last 30 days)
Yeeun Son on 20 Oct 2020
Commented: Yeeun Son on 20 Oct 2020
Hi,
I'm struggling to store for loop outcome in matrix.
for x=33:0.5:35
%Then I write codes for fitting a mathematical model to a graph using x values of 0 to x to obtain parameters 1-5
f1= %code for fitting graph
%And then I write codes for calculating parameter 6
parameter 6 = blah blah
%For My final output inside the loop, I wrote:
output = [x f1.parameter1 f1.parameter2 f1.parameter3 f1.parameter4 f1.parameter5 parameter6]
%Parameter1-5 is extracted from
end
So the final outcome from the loop gives one row with 7 columns
I would like to store my data from my for loop in a matrix so that everytime it produces new output it puts it in the next row.
(So for x=33:0.5:35, it should give a matrix with 5 rows and 7 columns)
How can I acheive this?

Stephen on 20 Oct 2020
Edited: Stephen on 20 Oct 2020
With MATLAB it is generally much better to loop over indices (rather than over data values), then you can simply use those indices for accessing/storing data as required:
V = 33:0.5:35;
N = numel(V);
C = cell(1,N);
for k = 1:N
x = V(k);
C{k} = output;
end
M = vertcat(C{:}) % concatenate all vectors into one matrix
Yeeun Son on 20 Oct 2020
thank you so much!

Andy on 20 Oct 2020
y=1;
for x=33:0.5:35
%Then I write codes for fitting a mathematical model to a graph using x values of 0 to x to obtain parameters 1-5
f1= %code for fitting graph
%And then I write codes for calculating parameter 6
parameter 6 = blah blah
%For My final output inside the loop, I wrote:
output(y,:) = [x f1.parameter1 f1.parameter2 f1.parameter3 f1.parameter4 f1.parameter5 parameter6]
%Parameter1-5 is extracted from
y=y+1;
end
Stephen on 20 Oct 2020
To avoid potential bugs and inefficiency, output should be preallocated before the loop: