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

조회 수: 3 (최근 30일)
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 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