Storing values from a loop in an array

조회 수: 7 (최근 30일)
Jamie
Jamie 2025년 4월 22일
댓글: Jamie 2025년 4월 22일
Hi everyone!
I'm trying to run a loop that saves every value after every iteration until it reaches 0 at which point the loop ends.
My code is as follows:
for y = [y;]
if y>=0
dV_y = (dt/m)*((0.5*rho*C_D*S)-m*g);
dy = dV_y*dt;
y = y+dy;
end
end
The loop runs 1 time and doesn't save it as an array.
Any help will be greatly appreciated, thanks!

채택된 답변

Matt J
Matt J 2025년 4월 22일
편집: Matt J 2025년 4월 22일
N=1e7; %Maximum allowed number of iterations.
ysave=nan(1,N);
for i=1:N
dV_y = (dt/m)*((0.5*rho*C_D*S)-m*g);
dy = dV_y*dt;
y = y+dy;
ysave(i)=y;
if y<0,
break;
elseif i==N
warning 'Stopping threshold was not reached.'
end
end
y=ysave(1:i);
  댓글 수: 1
Jamie
Jamie 2025년 4월 22일
Hi Matt,
Thanks, worked like a charm!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by