store for loop outcomes in matrix

조회 수: 1 (최근 30일)
Yeeun Son
Yeeun Son 2020년 10월 20일
댓글: Yeeun Son 2020년 10월 20일
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

채택된 답변

Stephen23
Stephen23 2020년 10월 20일
편집: Stephen23 2020년 10월 20일
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개)

Andy
Andy 2020년 10월 20일
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
Stephen23
Stephen23 2020년 10월 20일
To avoid potential bugs and inefficiency, output should be preallocated before the loop:

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by