フィルターのクリア

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

1 回表示 (過去 30 日間)
D_coder
D_coder 2018 年 9 月 11 日
編集済み: Stephen23 2018 年 9 月 11 日
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