Storing data from a for loop in a matrix

70 ビュー (過去 30 日間)
CJ
CJ 2016 年 4 月 7 日
コメント済み: Ced 2016 年 4 月 7 日
Just getting started with Matlab and am running into some issues. I need to store the ouput from each step of the For Loop in a matrix. The following is my code:
% Set initial paramters.
Cl_initial=3;
R=0.5;
u=0.5;
Clt=0;
% Solve for Cl residual.
for t=[68.92 109.97 287.22 116.95 171.89 90.3 103.54];
Clt=[t; Cl_initial*(1-R)/(1-R*exp(-u*t))];
end
The way I have it set up now only saves the very last calculation in the matrix. Any help would be appreciated!

採用された回答

Ced
Ced 2016 年 4 月 7 日
編集済み: Ced 2016 年 4 月 7 日
Hi
There is a search feature in the forum, you will find hundreds of examples for this.
But your problem is that you are overwriting Clt in each iteration. The solution is to save each iteration in a new column (or row). Generally speaking, it is always good to pre-initialize data containers (in this case a matrix) before filling it in a loop.
Something like:
% Set initial paramters.
Cl_initial=3;
R=0.5;
u=0.5;
t=[68.92 109.97 287.22 116.95 171.89 90.3 103.54];
Nt = length(t);
Clt = zeros(2,Nt);
% Solve for Cl residual.
for i = 1:Nt
Clt(:,i) = [ t(i) ; Cl_initial*(1-R)/(1-R*exp(-u*t(i)))];
end
  2 件のコメント
CJ
CJ 2016 年 4 月 7 日
I now see what I was missing. Thanks for the quick response.
Ced
Ced 2016 年 4 月 7 日
Sure. You can "accept" the answer to close the topic if your problem was solved. Thanks!

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 4 月 7 日
Cl_initial=3;
R=0.5;
u=0.5;
Clt=[];
% Solve for Cl residual.
for t=[68.92 109.97 287.22 116.95 171.89 90.3 103.54]
Clt=[Clt;t Cl_initial*(1-R)/(1-R*exp(-u*t))]
end

カテゴリ

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