Using MATLAB to find the max elements and their positions

11.4k Views Asked by At

MATLAB documentation says

"[C,I] = max(...) finds the indices of the maximum values of A, and returns them in output vector I."

But that does not seem to work. See below.

X = [2 8 4; 7 3 9];

[a,b] = max(X)

a =

 7     8     9

b =

 2     1     2

The indices could have been given as linear indices b = [ 2 3 6] so that X(b) would give the max values of columns of X in a.

It looks like an error in MATLAB because the doc says something but it does something different.

3

There are 3 best solutions below

0
On

If you give max a matrix, it finds the maximum of each column. So $a = [7,8,9]$ and $b = [2,1,2]$ because the maximum of the first column is $7$, found in the second row, the maximum of the second column is $8$, found in the first row, and the maximum of the third column is $9$, found in the second row.

10
On

As it is stated at Robert Israel's answer, max only returns the indeces for the columns. This is illustrated for $3\times3$ matrix as below:

$\begin{bmatrix}1 & 1 & 1\\ 2 & 2 & 2\\ 3 & 3 & 3 \end{bmatrix}$

If you want to get indeces of the actual matrix, you need a workaround. If you run the following code X(b) gives the maximum values for each column.

m=size(X,1);
for i=2:size(b,2)
b(i)=b(i)+m;
m=m+size(X,1);
end

You can make your own max function by developing this code.

1
On

There is no error. The documentation is very clear about what it returns. If the linear indices are what you want, then you can get them with something like the following:

maxinds = sub2ind( size(X), b, [1:size(X,2)] );