繁体   English   中英

MATLAB查找最接近向量的捷径?

[英]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 

norm不能直接应用于矩阵的每一列或每一行,因此可以使用arrayfun

dist = arrayfun(@(col) norm(input_vector - candidate_vector(:,col)), 1:width);
[cmin, match_col] = min(dist);

此解决方案也在此处给出。

但是 ,此解决方案比使用bsxfun进行直接计算要慢得多(如Luis bsxfun的回答),因此应避免使用它。 应该将arrayfun用于更复杂的功能,在这些功能中很难实现矢量化方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM