Save data from for loop without subscript index

I am programming a simulation of a falling object and I want to plot its trajectory. When plotting I experience the problem that the data is not stored.
I want to plot h as function of t without its data being overwritten.
I also want the steps in each iteration to be 0.1, so indexing will not work.
The standard solution for these plots is using 'indexing' h(t). This does not work because the subscript index 't' starts with '0' and has steps of 0.1.
My code:
t0 = 0; %start time is 0 sec.
dt = 0.1; % timestep is 0.1 sec.
t_stop = 10; % time stops at 10 sec if h=0 has not been reached.
h0= 30; %start height
g = 9.81; %gravitational constant.
for t = t0:dt:t_stop %starttime:timestep:stoptime
h= h0-0.5*g*(t)^2; %h as function of t
if h=<0 %stop simulation when h=<0
break
end
end
Question: how to plot 'h' as function of 't'?

 채택된 답변

Guillaume
Guillaume 2019년 8월 2일
편집: Guillaume 2019년 8월 2일

0 개 추천

%... constant definitions
timesteps = t0:dt:t_stop;
h = zeros(size(timesteps)); %preallocate h
for step = 1:numel(timesteps)
t = timesteps(step);
h(step) = h0-0.5*g*t^2;
if h(step)<= 0
break;
end
end
Note that the whole thing can be done without a loop:
%... constant definitions
t = t0:dt:t_stop;
h = h0 - 0.5*g*t.^2; %note the .^ since t is a vector

댓글 수: 3

This is not a working solution:
I want to plot 'h' as a function of 't', but it has to stop when the condition h<=0 is met.
This answer keeps running until t=t_stop, in that way 'h' can be negative which is faulty.
The loop stops as soon as h is negative. You can then shorten the vectors if you so wish (otherwise it's just 0s)
%... constant definitions
timesteps = t0:dt:t_stop;
h = zeros(size(timesteps)); %preallocate h
for step = 1:numel(timesteps)
t = timesteps(step);
h(step) = h0-0.5*g*t^2;
if h(step)<= 0
break;
end
end
tokeep = h > 0;
plot(timesteps(tokeep), h(tokeep));
You can do the same with the vectorised method
%... constant definitions
t = t0:dt:t_stop;
h = h0 - 0.5*g*t.^2; %note the .^ since t is a vector
tokeep = h > 0;
plot(t(tokeep), h(tokeep));
%optional:
t = t(tokeep);
h = h(tokeep);
Wow, You da man!
Thank you very much

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Automotive에 대해 자세히 알아보기

질문:

2019년 8월 2일

댓글:

2019년 8월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by