Tomas
Tomas

Reputation: 89

Find the row/column of all maximum values in each row of a matrix

I want search indexes maximum value/s in each row. If row has more than one maximum, so I want to save both indexes.

For example:

X = [5 6 8
     1 2 3
     4 4 0];

And I need indexes

inds = [1 3
        2 3
        3 1
        3 2];

I wanted to use function max but this function only saves one index.

Upvotes: 2

Views: 908

Answers (2)

Max
Max

Reputation: 1481

Another way to do it, would be to use max and repmat. First you find the maximum of each row using

rowMaximum=max(X,[],2);

Then you replicate the maximum so that it has the same dimension as your input and compare it to the input

logicalMaximum=repmat(rowMaximum,1,size(X,2))==X;

And the last thing you wanna do is converting this logical array into your desired indexes

[columns,rows]=find(logicalMaximum);
result=[rows,columns];

Upvotes: 0

Suever
Suever

Reputation: 65460

You can use max to compute the max for each row and then compare the elements in each row to it's row-wise max using bsxfun and eq. Then you can find the row/column positions of these maxima. We use a transpose in there (.') to ensure that we get the ordering of the output that you expect.

[c,r] = find(bsxfun(@eq, d, max(d, [], 2)).')
output = [r,c];

Upvotes: 3

Related Questions