Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Finding the row and column number in a matrix

Asked by Raghuram on 15 Mar 2011

for a matrix [1 2 3 4 6 10 7 5 9] mXn matrix-- how is it that i can find the min or max element and then find the row number and the column number for further use in calculations




No products are associated with this question.

3 Answers

Answer by Jan Simon on 15 Mar 2011
Accepted answer
data = rand(5, 3);
[maxNum, maxIndex] = max(data(:));
[row, col] = ind2sub(size(data), maxIndex);

Another less compact approach finds the max values for each column at first:

data = rand(5, 3);
[maxNumCol, maxIndexCol] = max(data);
[maxNum, col] = max(maxNumCol);
row = maxIndexCol(col);

Please read "help max" also.


Raghuram on 26 Mar 2011

I used the first method only this time
the code was
[minNum1, minIndex1] = min(f(:));
[row1, col1] = ind2sub(size(f(:)), minIndex1);

??? Attempted to access pg(32,1); index out of bounds because size(pg)=[30,2].

Error in ==> PSO1stage5double at 155

is there any mistake in the code, the notations i mean

Walter Roberson on 26 Mar 2011

Don't use size(f(:)), use size(f)

Raghuram on 26 Mar 2011

yea it works now, thank you :)

Jan Simon
Answer by Rajashree Jain on 15 Mar 2011

[val row]=max(A(:));

[val col]=max(A(row,:));

[val row col];

1 Comment

Jan Simon on 15 Mar 2011

This will not work. In the first line you can get e.g. the last element of A as maximum, then "row==numel(A)". Then "A(row, :)" will fail.

Rajashree Jain
Answer by Amey on 15 Mar 2011

The first answer given by Jan Simon is absolutely right and the most efficient way to do it.



Contact us