MATLAB Answers

Vectorial expression or for loop?

1 view (last 30 days)
Hello there,
I was wondering whether the following expressions are perfectly equivalent.
Unfortunately, I get two slightly different results.
First expression:
for i = 2:length(time)
delta_t_averaged = mean(time(i) - time(i - 1));
Second expression:
delta_t_averaged = mean(time(2:end) - time(1:(end - 1)));


Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 7 Nov 2019
Those expressions are not even close to being the same.
In the first expression, i is scalar, so time(i) is scalar and time(i-1) is scalar, so time(i)-time(i-1) is scalar. mean() of a scalar is the same scalar as if mean() had not been called. You then assign that result to all of delta_t_averaged, overwriting everything that had been done before. The end result is going to be time(end)-time(end-1) assigned to delta_t_averaged.
In the second expression, time(2:end) - time(1:(end - 1)) is a vector expression. mean() of the vector expression is sum() of the vector divided by the length of the vector. Consider time(2)-time(1) + time(3)-time(2) + time(4)-time(3) ... and you can see that algebraically the time(2) at the beginning cancels with the time(2) subtracted from time(3), and the time(3) there cancels with the subtracted time(3) in the next term, and so on. The end result of the sum would be time(end)-time(1) . You would then divide that by (length(time)-1) . The result would be quite different than the time(end)-time(end-1) calculated by the first loop.

  1 Comment

john_arle on 7 Nov 2019
Thank you. Shame on me hahah!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!