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

3 vues (au cours des 30 derniers jours)
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

Réponse acceptée

David Sanchez
David Sanchez le 16 Mai 2014
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 commentaire
Jennet C JB
Jennet C JB le 16 Mai 2014
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by