这个for循环可以矢量化以提高速度吗

Can this for loop be vectorized for speed

我需要找出H_A的每个元素与H_B中的每个元素的区别,这是我的方法

              H_A=reshape(H_A,1,[]);
              H_B=reshape(H_B,1,[]);
              for i=1:SIZE^2
              D(i,:)=((H_A(i)-H_B)).^2;
              end

能否将其矢量化以提高速度。

试试 bsxfun。

H_A = reshape(H_A, [], 1);
H_B = reshape(H_B, 1, []);
D = bsxfun(@minus, H_A, H_B).^2;

您可以使用广播:

H_A = reshape(H_A, [], 1);
H_B = reshape(H_B, 1, []);
(H_A-H_B).^2;

可能是最快的选择。还有 pdist2 可以让你计算不同的距离指标:

H_A = reshape(H_A, [], 1);
H_B = reshape(H_B, [],1);
pdist2(H_A,H_B,'squaredeuclidean')