【问题标题】:Check Proximity of Point in Matlab在 Matlab 中检查点的接近度
【发布时间】:2018-07-17 21:10:03
【问题描述】:

我有数组 A。如何对其进行编码,以便将第一行与第二行、第二行与第三行以及第三行与第四行进行比较。如果欧几里得距离小于1,则从数组A中省略,否则保留在其中。

A=[ 1.05, 33.43; 1.66, 30.81; 1.78, 30.98; 2.01, 28.05]
A=sortrows(A,[1,2])
for i=size(A,1)
      if (sum(A(i,:)-A(i+1)).^2, 2)<1
          A(i+1,:)=[ ]
      end
end

请提出更正建议。

【问题讨论】:

    标签: matlab for-loop while-loop conditional


    【解决方案1】:

    您可以通过在A 的行上使用不同的索引器来创建差异:

    A = [1.05, 33.43; 1.66, 30.81; 1.78, 30.98; 2.01, 28.05];
    A = sortrows(A,[1 2]);
    
    A1 = A(1:end-1,:);
    A2 = A(2:end,:);
    

    完成此操作后,欧几里得距离可以以矢量化方式计算,其性能通常比 Matlab 中的for 循环要好得多:

    D = sqrt(sum((A1 - A2) .^ 2,2));
    
    % this is because the computation is performed on *rows-1*, hence the
    % indexation must be adjusted in order to produce the correct result
    D = [Inf; D]; 
    

    最后只保留距离大于等于1的点:

    A(D >= 1,:)
    
    ans =
        1.0500   33.4300
        1.6600   30.8100
        2.0100   28.0500
    

    【讨论】:

      【解决方案2】:

      您发布的代码中有几个错误:

      • for 语句中缺少初始值
      • 也应该终止于size(A,1)-1
      • “if”语句中缺少一些括号
      • square root 在计算中缺少euclidean distance
      • 您不应该在循环中删除初始矩阵的行

      一个可能的解决方案是:

      A=[ 1.05, 33.43; 1.66, 30.81; 1.78, 30.98; 2.01, 28.05]
      A=sortrows(A,[1,2])
      % Make a copy of the original matrix
      B=A
      % Loop over the matrix rows
      for i=1:size(A,1)-1
         % Evaluate the Euclidean Distance and store it in an array (for verification purpose)
         ed(i)=sqrt(sum((A(i,:)-A(i+1,:)).^2))
         % If the Euclidean Distance is less than the threshold, delete the row in the
         % B matrix
         if(ed(i) < 1) 
                B(i+1,:)=[]
            end
      end
      

      这给出了:

      欧几里得距离

      ed =
      
         2.69007   0.20809   2.93901
      

      原始矩阵

      A =
      
          1.0500   33.4300
          1.6600   30.8100
          1.7800   30.9800
          2.0100   28.0500
      

      更新矩阵

      B =
      
          1.0500   33.4300
          1.6600   30.8100
          2.0100   28.0500
      

      原始矩阵的第三行已被删除,即欧几里得距离等于0.20809

      【讨论】:

        猜你喜欢
        • 2012-11-14
        • 2019-07-19
        • 1970-01-01
        • 2023-03-29
        • 2019-04-09
        • 1970-01-01
        • 1970-01-01
        • 2012-11-30
        • 1970-01-01
        相关资源
        最近更新 更多