1

I have two Euclidian distance functions, one that uses bsxfun while the other uses repmat. They gave slightly different results, on Matlab 2012a, OSX. For example

x = randn(32, 50);
y = randn(32, 50);

xx = sum(x.*x, 1); 
yy = sum(y.*y, 1); 
xy = x'*y; 

d1 = sqrt(abs(repmat(xx', [1 size(yy, 2)]) + repmat(yy, [size(xx, 2) 1]) - 2*xy));
d2 = sqrt( abs(bsxfun(@plus, xx', bsxfun(@minus, yy, 2*xy)) ));

isequal(d1, d2)

figure;hist(d1(:)-d2(:), 50)

Gives: enter image description here

Why is this, or am I missing something here?

Maurits
  • 2,014
  • 3
  • 27
  • 31
  • 2
    For more information beyond the answer as to why, see [Is Floating point addition and multiplication associative?](http://stackoverflow.com/questions/10371857/is-floating-point-addition-and-multiplication-associative) and, from the linked answer, [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – TroyHaskin Aug 03 '16 at 20:56
  • @TroyHaskin Thanks! – Maurits Aug 03 '16 at 22:23

1 Answers1

4

The order of operations you're doing is different. Put parenthesis like so

 d1 = sqrt(abs(repmat(xx', [1 size(yy, 2)]) + (repmat(yy, [size(xx, 2) 1]) - 2*xy)));

and you'll get the same result

hiandbaii
  • 1,226
  • 8
  • 14