How to save last three values from for loop?

3 vues (au cours des 30 derniers jours)
Muhammad Usman
Muhammad Usman le 17 Jan 2021
I just got stuck to save the last three values of r from the for loop, please help me in this regard.
yl = 1;
rl = [0, yl] ;
speed = 50;
theta = 45;
vl = [speed*cos(theta*pi/180), speed*sin(theta*pi/180)];
r = rl; v = vl;
Cd = 0.35; area = 4.3e-3; grav =9.81; mass = 0.145; rho = 1.2; air_const = -0.5*Cd*rho*area/mass;
tau = 0.1;
maxstep = 1000;
for i=1:maxstep
xplot(i) = r(1) ;
yplot(i) = r(2);
t = (i-1)*tau;
xNoAir(i) = rl(1) + vl(1)*t;
yNoAir(i) = rl(2) + vl(2)*t - 0.5*grav*t^2;
accel = air_const*norm(v) *v;
accel(2) = accel (2)-grav;
r = r + tau*v;
v = v + tau*accel;
if( r(2) < 0 )
xplot(i+1) = r(1);
yplot(i+1) = r(2);
break ;
end
end
Thanks for help.

Réponses (1)

KALYAN ACHARJYA
KALYAN ACHARJYA le 17 Jan 2021
Modifié(e) : KALYAN ACHARJYA le 17 Jan 2021
Save the loop results in array (if scalar data) or in cell arary (in vector results) are good ways to handle the data. From the code it has been observe that r is array vector, I suppose you are considering last three r vectors generated by r, please do accordingly, you may use cell array
r=cells(1,maxstep);
r{1}=rl;
for i=1:maxstep
r{i}=
end
Here all evaluated values of r are saved in the cell array. Using indexing, you can get the lat three cell elements
r{maxstep-2:maxstep}
Hoep you can modify the code and do that same. Any issue let me know

Catégories

En savoir plus sur Matrix Indexing 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