store for loop outcomes in matrix

1 Ansicht (letzte 30 Tage)
Yeeun Son
Yeeun Son am 20 Okt. 2020
Kommentiert: Yeeun Son am 20 Okt. 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?
Many thanks in advance

Akzeptierte Antwort

Stephen23
Stephen23 am 20 Okt. 2020
Bearbeitet: Stephen23 am 20 Okt. 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);
... your code
C{k} = output;
end
M = vertcat(C{:}) % concatenate all vectors into one matrix

Weitere Antworten (1)

Andy
Andy am 20 Okt. 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
  1 Kommentar
Stephen23
Stephen23 am 20 Okt. 2020
To avoid potential bugs and inefficiency, output should be preallocated before the loop:

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by