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

1 view (last 30 days)
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 Comment
Stephen23
Stephen23 on 11 Sep 2018
Edited: Stephen23 on 11 Sep 2018
"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.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 11 Sep 2018
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!