store for loop outcomes in matrix

1 vue (au cours des 30 derniers jours)
Yeeun Son
Yeeun Son le 20 Oct 2020
Commenté : Yeeun Son le 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?
Many thanks in advance

Réponse acceptée

Stephen23
Stephen23 le 20 Oct 2020
Modifié(e) : Stephen23 le 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);
... your code
C{k} = output;
end
M = vertcat(C{:}) % concatenate all vectors into one matrix
  1 commentaire
Yeeun Son
Yeeun Son le 20 Oct 2020
thank you so much!

Connectez-vous pour commenter.

Plus de réponses (1)

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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by