enigmae
enigmae

Reputation: 349

Specific selection of rows from a matrix MATLAB

Consider the following the matrix:

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 
.
.
.

I want to select the row(s) with the maximum value in column 2 for every unique value in column 1.

For eg. Answer should be:

1 3 1 1
2 9 0 0
3 4 5 6
3 4 1 1

Any ideas?

Upvotes: 0

Views: 60

Answers (2)

Dan
Dan

Reputation: 45752

Here's one way:

%// 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, :)

Upvotes: 3

Amro
Amro

Reputation: 124573

Some code to get you started:

% 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{:});

The result for the matrix you've shown:

>> xx
xx =
     1     3     1     1
     2     9     0     0
     3     4     5     6
     3     4     1     1

Upvotes: 1

Related Questions