【问题标题】:finding locations of a set of elements in a matrix - Matlab在矩阵中查找一组元素的位置 - Matlab
【发布时间】:2012-03-02 16:04:32
【问题描述】:

我有一个矩阵 A 。 我想找到所有独特的元素是 A 所以: b = 唯一(A);将给出 A 中所有唯一元素的数组。

我想找到这些元素在A中的位置。准确的说是b中的元素 在 A 中重复自己,我想为 b 中的每个元素找到它在 A 中的 rows

如何在没有循环的情况下做到这一点?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    命令

    [b,m,n] = unique(A);
    

    应该为您提供回答问题所需的所有数据。

    【讨论】:

      【解决方案2】:

      以下是一些示例代码,可以完成我认为您正在尝试做的事情:

      %Test data
      A = [...
          1 2 3 4; ...
          4 5 6 7; ...
          8 1 3 4];
      
      %Basic "unique" call
      [B, ix_A, ix_B] = unique(A);
      
      %Note that the indexes from unique can be used as follows
      isequal(A(ix_A), B )   %Returns true
      isequal(B(ix_B), A(:) )   %Returns true
      
      %To find a row (and column) in A where each element in B can be found we
      %just need to convert the linear indexs into row/column subscripts
      [row, column] = ind2sub(size(A), ix_A);
      %     Note that in general, multiple rows will contain each value from A.
      %     This will always produce one of the rows (and columns), pracitcially,
      %     it looks like to returns the last row containing the value.
      

      【讨论】:

      • 您可以通过将“first”或“last”传递给 unique 函数来控制返回的索引是该值的第一次还是最后一次出现。如果你想找到唯一的行而不是唯一的元素,你也应该传递“行”。
      • 我对这个问题的理解是需要每个元素的唯一值,而不是唯一的行。但这是一个很好的观点。我不知道unique 支持'first' 和'last' 关键字。这是一个很好的提示。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 2015-04-15
      • 1970-01-01
      • 2014-04-30
      相关资源
      最近更新 更多