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 个评论
回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!