How to save last three values from for loop?
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
KALYAN ACHARJYA
2021-1-17
编辑:KALYAN ACHARJYA
2021-1-17
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!