从矩阵matlab中获取最有价值的元素

时间:2014-03-07 22:31:59

标签: arrays matlab indexing max

我有像这样的矩阵nx3

A = [ 1 3 50;
      1 4 80;
      1 6 75;
      2 3 20;
      3 6 10;
      6 8 20;
      6 9 99;
      . . .
      . . .
    ]

我想检查第一个有相同的索引  =>检查第三个元素并选择最大值并重新排列矩阵

它应该像

Ans = [1 4 80;
       2 3 20;
       6 9 99;
       . . .
      ]

我在考虑使用max()检查第三个元素但是如何检测矩阵上重复的第一个元素

2 个答案:

答案 0 :(得分:2)

%// Obtain unique values of col 1. Each value will determine a group of rows:
ii = unique(A(:,1));
%// For each group of rows, compute maximum of column 3. This is done efficiently
%// with accumarray. Use its sparse option to avoid memory problems , in case
%//  values of column 1 are very disperse:
kk = nonzeros(accumarray(A(:,1),A(:,3),[],@max,[],true));
%// Select indices of rows whose column 3 contains the maximum of the group
%// determined by column 1. This is done efficiently using bsxfun twice:
m = any(bsxfun(@eq, A(:,1).', ii) & bsxfun(@eq, A(:,3).', kk));
%// Build result:
result = A(m,:);

在你的例子中:

result =

     1     4    80
     2     3    20
     3     6    10
     6     9    99

答案 1 :(得分:2)

产生与Luis Mendo

相同的结果
Ans = sortrows(A, 3);
[~, J] = unique(Ans(:,1));
Ans = Ans(J,:);