2

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.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Tomas
  • 89
  • 7

2 Answers2

3

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];
Suever
  • 64,497
  • 14
  • 82
  • 101
0

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];
Max
  • 1,471
  • 15
  • 37
  • It's worth noting the extreme speedup that `bsxfun` offers over `repmat` for `eq` shown in [this extensive answer](http://stackoverflow.com/a/29719681/670206) – Suever Apr 12 '17 at 02:21