Vectorial expression or for loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
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)));
댓글 수: 0
채택된 답변
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!