考虑以下矩阵:
1 2 1 1
1 3 1 1
2 5 2 3
2 6 2 4
2 6 2 4
2 9 0 0
3 4 5 6
3 4 1 1
3 2 0 0
3 1 1 1
.
.
.
我想为第1列中的每个唯一值选择第2列中具有最大值的行。
例如。 答案应该是:
1 3 1 1
2 9 0 0
3 4 5 6
3 4 1 1
有什么想法吗?
答案 0 :(得分:3)
这是一种方式:
%// Get a unique list of column 1 without changing the order in which they appear
[C1, ~, subs] = unique(M(:,1), 'stable');
%// Get the max value from column 2 corresponding to each unique value of column 1
C2 = accumarray(subs, M(:,2), [], @max);
%// Find the desired row indices
I = ismember(M(:,1:2), [C1, C2], 'rows');
%//Extract the rows
M(I, :)
答案 1 :(得分:1)
一些代码可以帮助您入门:
% unique values in first column
col1 = unique(x(:,1));
% we first store results in a cell array (later converted to matrix)
xx = cell(numel(col1), 1);
for i=1:numel(col1)
% rows with the same value in column 1
rows = x(x(:,1) == col1(i),:);
% maximum value along column 2
mx = max(rows(:,2));
% store all rows with the max value (in case of ties)
xx{i} = rows(rows(:,2)==mx,:);
end
% combine all resulting rows
xx = vertcat(xx{:});
您显示的矩阵的结果:
>> xx
xx =
1 3 1 1
2 9 0 0
3 4 5 6
3 4 1 1