BigList = rand(20, 3)
LittleList = rand(5, 3)
I\'d like to find for each row in the big list the \'closest\' row in the little list, as defined by
The proper way is of course using nearest-neighbor searching algorithms.
However, if your dimension is not too high and your data sets are not big than you can simply use bsxfun:
d = bsxfun( @minus, permute( bigList, [1 3 2] ), permute( littleList, [3 1 2] ) ); %//diff in third dimension
d = sum( d.^2, 3 ); %// sq euclidean distance
[minDist minIdx] = min( d, [], 2 );
In addition to Matrix multiplication approach proposed here, there is another matrix multiplication without loops
nb = sum( bigList.^2, 2 ); %// norm of bigList's items
nl = sum( littleList.^2, 2 ); %// norm of littleList's items
d = bsxfun( @sum, nb, nl.' ) - 2 * bigList * littleList'; %// all the distances
The observation behind this method is that for Euclidean distance (L2-norm)
|| a - b ||^2 = ||a||^2 + ||b||^2 - 2
With being the dot product of the two vectors.