[英]MATLAB short way to find closest vector?
在我的应用程序中,我需要在一组向量(即矩阵)中找到与输入向量最接近的(最小欧氏距离向量)
因此,每一次我都必须这样做:
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
是否有内置的MATLAB函数可以轻松地(用少量代码)完成这种事情?
谢谢你的帮助 !
使用pdist2
。 假设(从您的代码中)向量是列,因此需要转置,因为pdist2
与行一起使用:
[cmin, match_col] = min(pdist2(vectors.', input_vector.' ,'euclidean'));
也可以使用bsxfun
(在这种情况下,直接使用列更容易):
[cmin, match_col] = min(sum(bsxfun(@minus, vectors, input_vector).^2));
cmin = sqrt(cmin); %// to save operations, apply sqrt only to the minimizer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.