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 件のコメント
Yeeun Son
Yeeun Son 2020 年 10 月 20 日
thank you so much!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by