【问题标题】:MATLAB short way to find closest vector?MATLAB找到最近向量的捷径?
【发布时间】:2014-04-20 00:25:25
【问题描述】:

在我的应用程序中,我需要在一组向量(即矩阵)中找到与输入向量“最接近”(最小欧几里得距离向量)

因此每次我都必须这样做:

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 函数可以为我轻松完成这种事情(只需少量代码)?

感谢您的帮助!

【问题讨论】:

标签: matlab for-loop vector built-in euclidean-distance


【解决方案1】:

使用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 

【讨论】:

  • 非常感谢!我实际上不需要 cmin 值。我只需要match_col@minus 操作员在做什么?如果是@plus,那么它会返回最远的向量吗?
  • @minus 只是用于计算欧几里得距离(在每个平方项内)的减号。要找到最远的向量,请将min 更改为max(保持@minus
  • 好的,我现在没有时间尝试,但我相信这是正确的答案。再次感谢!
【解决方案2】:

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

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

这个解决方案也给here

但是,这个解决方案是much much slower,而不是使用bsxfun 进行直接计算(如Luis Mendo 的回答),所以应该避免。 arrayfun 应该用于更复杂的函数,其中矢量化方法更难获得。

【讨论】:

  • 是的,正是我写给你的。那么我应该删除它吗?
  • 这不是最快的方法,但我认为它不应该被删除。
  • 我用警告和你的链接编辑了它,所以很明显这不应该是首选的解决方案。
猜你喜欢
  • 2011-02-22
  • 2012-05-25
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 2016-01-08
  • 2015-01-10
  • 2022-08-14
相关资源
最近更新 更多