matlab bsxfun数值精度

时间:2016-08-03 20:45:57

标签: matlab bsxfun

我有两个欧几里德距离函数,一个使用bsxfun而另一个使用repmat。他们在Matlab 2012a,OSX上给出了略微不同的结果。例如

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)

给出: enter image description here

为什么会这样,或者我在这里遗漏了什么?

1 个答案:

答案 0 :(得分:4)

您正在执行的操作顺序不同。像这样放括号

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

并且您将得到相同的结果