【问题标题】:Matrix operation without loop无循环矩阵运算
【发布时间】:2017-08-06 07:45:26
【问题描述】:

我有一个包含 5 个点的几何坐标的矩阵。

centroids = [x1,x2;...;x5,y5]

我想构建一个包含与所有其他点的距离的矩阵。

distance  =

     inf         pt1-pt2     pt1-pt3     pt1-pt4     pt1-pt5
     pt2-pt1     inf         pt2-pt3     pt2-pt4     pt2-pt5
     pt3-pt3     pt3-pt2     inf         pt3-pt4     pt3-pt5
     pt4-pt1     pt4-pt2     pt4-pt3     inf         pt4-pt5
     pt5-pt1     pt5-pt2     pt5-pt3     pt5-pt4     inf

我使用 inf 是因为我想用每行 [value,index]=min(distance(.....)) 的索引取最小值。

目标是有一个像这样的最终矩阵:

result =
     indice_of_the_closest      dist
     indice_of_the_closest      dist
     indice_of_the_closest      dist
     indice_of_the_closest      dist
     indice_of_the_closest      dist

我通过循环实现了这一点,但我需要一些帮助才能在没有循环的情况下做到这一点。

最好的问候

【问题讨论】:

    标签: matlab matrix


    【解决方案1】:

    如果你没有统计工具箱,你可以这样做

    % Compute the pair-wise distances
    d = sqrt((x(:,1) - x(:,1).').^2 + (x(:,2) - x(:,2).').^2);
    
    % If you are on MATLAB < 2016b
    % d = sqrt(bsxfun(@minus, x(:,1), x(:,1).').^2 + bsxfun(@minus, x(:,2), x(:,2).').^2);
    
    % Set the diagonal to Inf
    d(logical(eye(size(d)))) = Inf;
    
    % Find the minimum distance and index
    [mindist, ind] = min(d, [], 1);
    
    % Create the output matrix
    result = [ind(:), mindist(:)];
    

    如果你确实有统计工具箱,你可以使用knnsearch找到离每个点最近的两个点(第一个最接近的是点本身)

    [inds, dists] = knnsearch(x, x, 'k', 2);
    result = [inds(:,2), dists(:,2)];
    

    【讨论】:

    • 您能详细解释一下 MATLAB
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    相关资源
    最近更新 更多