Finding the row and column number in a matrix

92 Ansichten (letzte 30 Tage)
Raghuram
Raghuram am 15 Mär. 2011
Kommentiert: Meryem am 4 Sep. 2014
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
  1 Kommentar
Meryem
Meryem am 4 Sep. 2014
You can have an answer with a few lines of code which is:
%you have ndata matrix
[r,c] = size(ndata); %get row and column values of data matrix
fprintf('\nRow of data matrix is: %d' ,r); %print number of row
fprintf('\nColumn of data matrix is: %d ' ,c); %print number of column

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 15 Mär. 2011
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.
  13 Kommentare
Walter Roberson
Walter Roberson am 26 Mär. 2011
Don't use size(f(:)), use size(f)
Raghuram
Raghuram am 26 Mär. 2011
yea it works now, thank you :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Rajashree Jain
Rajashree Jain am 15 Mär. 2011
[val row]=max(A(:));
[val col]=max(A(row,:));
[val row col];
  1 Kommentar
Jan
Jan am 15 Mär. 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.

Melden Sie sich an, um zu kommentieren.


Amey
Amey am 15 Mär. 2011
The first answer given by Jan Simon is absolutely right and the most efficient way to do it.

Kategorien

Mehr zu Performance and Memory finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by