How to save last three values from for loop?

2 views (last 30 days)
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 ;
Thanks for help.

Answers (1)

KALYAN ACHARJYA on 17 Jan 2021
Edited: KALYAN ACHARJYA on 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
for i=1:maxstep
Here all evaluated values of r are saved in the cell array. Using indexing, you can get the lat three cell elements
Hoep you can modify the code and do that same. Any issue let me know


Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!