0

I need to find out the difference of every element of H_A with every element in H_B, here is my approach

              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

can this be vectorized for speed.

USERNEW
  • 17
  • 5
  • The dupe is for 3D points, this question is for 1D points. But the answers over there actually work for any number of dimensions, including 1. – Cris Luengo Apr 26 '20 at 20:11

2 Answers2

1

Try bsxfun.

H_A = reshape(H_A, [], 1);
H_B = reshape(H_B, 1, []);
D = bsxfun(@minus, H_A, H_B).^2;
weiyin
  • 6,819
  • 4
  • 47
  • 58
1

You could use broadcasting:

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

Probably the fastest option. There is also pdist2 which allows you to calculate different distance metrics:

H_A = reshape(H_A, [], 1);
H_B = reshape(H_B, [],1);
pdist2(H_A,H_B,'squaredeuclidean')
Daniel
  • 36,610
  • 3
  • 36
  • 69