Reputation: 13653
In my application, I need to find the "closest" (minimum Euclidean distance vector) to an input vector, among a set of vectors (i.e. a matrix)
Therefore every single time I have to do this :
function [match_col] = find_closest_column(input_vector, vectors)
cmin = 99999999999; % current minimum distance
match_col = -1;
for col=1:width
candidate_vector = vectors(:,c); % structure of the input is not important
dist = norm(input_vector - candidate_vector);
if dist < cmin
cmin = dist;
match_col = col;
end
end
is there a built-in MATLAB function that does this kind of thing easily (with a short amount of code) for me ?
Thanks for any help !
Upvotes: 1
Views: 204
Reputation: 112699
Use pdist2
. Assuming (from your code) that your vectors are columns, transposition is needed because pdist2
works with rows:
[cmin, match_col] = min(pdist2(vectors.', input_vector.' ,'euclidean'));
It can also be done with bsxfun
(in this case it's easier to work directly with columns):
[cmin, match_col] = min(sum(bsxfun(@minus, vectors, input_vector).^2));
cmin = sqrt(cmin); %// to save operations, apply sqrt only to the minimizer
Upvotes: 4
Reputation: 2652
norm
can't be directly applied to every column or row of a matrix, so you can use arrayfun
:
dist = arrayfun(@(col) norm(input_vector - candidate_vector(:,col)), 1:width);
[cmin, match_col] = min(dist);
This solution was also given here.
HOWEVER, this solution is much much slower than doing a direct computation using bsxfun
(as in Luis Mendo's answer), so it should be avoided. arrayfun
should be used for more complex functions, where a vectorized approach is harder to get at.
Upvotes: 3