do math operation on two arrays of different sizes

491 Views Asked by At

so I'm trying to find the minimum distance between each point in a large array with that of a smaller array. The following works for a single point.

m = [-3, -1, 1, 3];
r = [.2, -1, .39, 3.6, -1.8.....]
[minVal ind] = min((r(1) - m).^2))

What i'm trying to do it this:

[minVal ind] = min((r - m).^2))

Where it does (r(1) -m)^2, and finds the minimum, and then does (r(2) -m)^2, and finds the minimum, etc. I know this could be done in a for loop, I just thought there would be a more elegant solution. I hope that makes sense. Thanks for your time!

2

There are 2 best solutions below

1
On BEST ANSWER

Try this:

m = [-3, -1, 1, 3]
r = [.2, -1, .39, 3.6, -1.8]

%// bsxfun makes the matrix of all pairwise squared differences efficiently
F=bsxfun(@(x,y) (x-y).^2,m.',r);

%// Find the minimum and it's row/column indices
[minVal,I] = min(F(:));
[row,col]=ind2sub(size(F),I)

minVal
m(row)
r(col)

Note that you could replace your distance function with abs(x-y) instead of (x-y).^2 for the same result, or even make F by doing F=pdist2(m.',r.').

0
On

You can do this using matrix operation to avoid loop in Matlab. Use repmat() to generate two matrix with dimension of length(r)*length(m). Subtract the two matrix, square and then use min() to get the minimum of each column or row of the resulted matrix.