How do I use two vectors of velocity and time and a for loop to find distance?
3 views (last 30 days)
Show older comments
I have two vectors:
vel=[10,15,17,18]; % velocity [km/h]
time=[0.5,1,2,3]; % time [h]
and the equation:
distance=vel*time; % compute distance traveled [km]
I want to use a for loop to find distance as a function of time. I can't figure out what I should input as my initial value, step, or final value.
0 Comments
Answers (2)
Walter Roberson
on 16 Oct 2022
If the time vector is the times at which events start, then you need to take the differences in time in order to find out the duration of the step. Likewise if the time vector is the time at which events end (which probably makes more sense since you probably don't want to be sitting idle for 1/2 hour before travelling.)
distance=vel*time;
that equation is not wrong, but the time referred to there is the time spent traveling at that velocity.
Also you have to be careful about the fact that in MATLAB, the * operator is "inner product", algebraic matrix multiplication, but you would want element-by-element product, which in MATLAB is the .* operator.
0 Comments
Torsten
on 16 Oct 2022
I'd suggest
vel=[10,15,17,18]; % velocity [km/h]
time=[0.5,1,2,3]; % time [h]
vel = [0,vel];
time = [0,time];
distance(1) = 0;
for i = 2:numel(time)
distance(i) = distance(i-1) + (time(i)-time(i-1))*(vel(i)+vel(i-1))/2;
end
distance
2 Comments
Torsten
on 16 Oct 2022
Edited: Torsten
on 16 Oct 2022
It's only a warning, but allocate "distance" beforehand:
vel=[10,15,17,18]; % velocity [km/h]
time=[0.5,1,2,3]; % time [h]
vel = [0,vel];
time = [0,time];
distance = zeros(size(time));
for i = 2:numel(time)
distance(i) = distance(i-1) + (time(i)-time(i-1))*(vel(i)+vel(i-1))/2;
end
distance
See Also
Categories
Find more on Guidance, Navigation, and Control (GNC) 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!