Vectorial expression or for loop?

조회 수: 1 (최근 30일)
john_arle
john_arle 2019년 11월 7일
답변: Walter Roberson 2019년 11월 7일
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));
end
Second expression:
delta_t_averaged = mean(time(2:end) - time(1:(end - 1)));

채택된 답변

Walter Roberson
Walter Roberson 2019년 11월 7일
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
john_arle
john_arle 2019년 11월 7일
Thank you. Shame on me hahah!

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by