필터 지우기
필터 지우기

why does method 1 result not equal to method 2 result even if both perform the same thing ?

조회 수: 1 (최근 30일)
a = [2 5 2 9 ; 3 2 5 0; 4 5 9 2; 1 6 1 5]
threshold = 3
%function 1
z = 0;
for n = 1: size(a,1)
for m = 1: size(a,2)
if a(n,m) <threshold,
z = z + a(n,m)^2;
end
end
end
%function 2
z = sum((a(a<threshold)).^2)
  댓글 수: 1
Stephen23
Stephen23 2018년 9월 11일
편집: Stephen23 2018년 9월 11일
"even if both perform the same thing ?"
Because they are not the same thing. In general floating point operations are not commutative like algebra or symbolic mathematics is.

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

답변 (1개)

Walter Roberson
Walter Roberson 2018년 9월 11일
If your actual data is floating point rather than integer then the two do not do the same thing. The double nested loop sums across rows with a definite ordering. The vectorized version extracts the matching values in linear order, down columns, and passes it to a vector addition operator. The vector addition operator is permitted to add the values in any order it wants to. For large enough vectors it would pass the values to a high performance library that would segment the values according to the number of available CPUs, create a subtotal for each, and then add the subtotals.
The difference in order of addition matters for floating point because floating point addition is not commutative. A+B+C does not have to add to exactly the same thing as A+(B+C) adds to.

Community Treasure Hunt

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

Start Hunting!

Translated by