MATLAB - Need help storing values of previous iterations in a while loop

3 ビュー (過去 30 日間)
Jennet C JB
Jennet C JB 2014 年 5 月 16 日
コメント済み: Jennet C JB 2014 年 5 月 16 日
Ok. So I have a while loop that iterates for values of xcount and time. In the end, I need to plot all the xcount and time values. This should give me a simple harmonic plot. unfortunately, my while loop only stores the 'final' value for xcount and time. thus the plot produced is also wrong. Could someone please tell me where I have gone wrong. And how to fix it. Thanks
function [ X,t ] = spring( ks,rs,startx,d,m,c,tinc,atol,vtol )
X=startx;
t=0;
V=0;
a=0;
time = 0;
xcount=0;
F1=-ks(1)*(X-rs(1));
F2=ks(2)*(d-X-rs(2));
DampingF = c*V;
NetForce= F1 + F2 - DampingF;
a = (NetForce/m);
V = V + a*tinc;
t = t + tinc;
X = X + V*tinc;
xcount = [xcount X];
time = [time t];
while (abs(V) >= vtol) (abs(a) >= atol)
F1=-ks(1)*(X-rs(1));
F2=ks(2)*(d-X-rs(2));
DampingF = c*V;
NetForce= F1 + F2 - DampingF;
a =(NetForce/m);
V = V+(a*tinc);
X = X + V*tinc;
xcount = [0 X X];
t = t + tinc;
time = [0 tinc 2*tinc];
end
plot(xcount,time);
xlabel('x');
ylabel('Time');
end

採用された回答

David Sanchez
David Sanchez 2014 年 5 月 16 日
I think your while loop should go like this:
while (abs(V) >= vtol) && (abs(a) >= atol)
F1=-ks(1)*(X-rs(1));
F2=ks(2)*(d-X-rs(2));
DampingF = c*V;
NetForce= F1 + F2 - DampingF;
a =(NetForce/m);
V = V+(a*tinc);
X = X + V*tinc;
xcount = [xcount X];
t = t + tinc;
time = [time t];
end
  1 件のコメント
Jennet C JB
Jennet C JB 2014 年 5 月 16 日
thanks a lot David!!
yes I did try this, but once again this while loop only stores the final value of X and t in the workspace. I want the value after each iteration to be stored in a matrix.
So if I wanted to call the values of X and t in a future function, i wont be able to do this, since they are not the matrices that I need.

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

その他の回答 (0 件)

カテゴリ

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