Select specified (max) values

1 次查看(过去 30 天)
gianluca
gianluca 2017-2-12
编辑: Jan 2017-2-12
Dear all, I've a matrix, e.g.:
A = [2 1 1 1440 62 2 6 8; 2 2 1 1882 65 2 7 8; 3 1 1 820 51 2 5 8; 3 2 1 1435 65 2 6 8; 3 3 1 1608 67 2 6 8; 9 1 1 394 38 1 2 8;9 2 1 2198 93 2 9 8; 9 2 2 2198 91 2 12 8; 9 2 3 2198 92 2 16 8; 9 3 1 2994 122 1 7 8; 9 3 2 2994 125 1 10 8; 9 3 3 2994 126 1 14 8];
For each row with the same value in the 1st and 2nd column, I've to take only the row where the 3th column is the maximum. I would, as result, a matrix like this:
B = [2 1 1 1440 62 2 6 8; 2 2 1 1882 65 2 7 8; 3 1 1 820 51 2 5 8; 3 2 1 1435 65 2 6 8; 3 3 1 1608 67 2 6 8; 9 1 1 394 38 1 2 8; 9 2 3 2198 92 2 16 8; 9 3 3 2994 126 1 14 8];
[key, ~, index] = unique(A(:,[1 2]),'stable','rows');
x = accumarray(index, A(:,3), [], @max);
...and I'm blocked here!

采纳的回答

Jan
Jan 2017-2-12
编辑:Jan 2017-2-12
You can start with sorting the array according to the first 3 columns. Then take the rows which contain a change in the 1st or 2nd column, and the last row:
S = sortrows(A, 1:3); % Largest 3rd col to bottom
Index = [diff(S(:, 1)) | diff(S(:, 2)); true]; % 1st or 2nd col changes
B = A(Index, :) % Extract result

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by