why does method 1 result not equal to method 2 result even if both perform the same thing ?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Respuestas (1)
Walter Roberson
el 11 de Sept. de 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.
0 comentarios
Ver también
Categorías
Más información sobre Symbolic Math Toolbox en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!