How do I use two vectors of velocity and time and a for loop to find distance?

3 views (last 30 days)
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.

Answers (2)

Walter Roberson
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.

Torsten
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
distance = 1×5
0 2.5000 8.7500 24.7500 42.2500
  2 Comments
Eleanor Grace
Eleanor Grace on 16 Oct 2022
I tried this code, but got the error code on the line under the for code:
Variable appears to change size on every loop iteration (within a script). Consider preallocating for speed.
Do you know how I can fix this?
Torsten
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
distance = 1×5
0 2.5000 8.7500 24.7500 42.2500

Sign in to comment.

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!