这个for循环能否矢量化以提高速度[重复]。

问题描述 投票:0回答:2

我需要找出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

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

matlab vectorization
2个回答
1
投票

试试bsxfun。

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

1
投票

你可以用广播。

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')
© www.soinside.com 2019 - 2024. All rights reserved.