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

3 visualizaciones (últimos 30 días)
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

Respuesta aceptada

David Sanchez
David Sanchez el 16 de Mayo de 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 comentario
Jennet C JB
Jennet C JB el 16 de Mayo de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by