Search code examples
matlabbsxfun

matlab bsxfun numerical precision


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?


Solution

  • 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