KGB91
KGB91

Reputation: 679

Find the largest value in a column

I have a matrix like A below, although much larger in reality:

A =  2  100  250
     1  50   25
     0  600  700
     5  20   30

I want to find the row values based on the largest value in the first column. In my example above, I want to find the fourth row based on the column value "5" and also get its two other row values, 20 30.

Upvotes: 2

Views: 388

Answers (2)

EBH
EBH

Reputation: 10440

Using logical indexing you can do it compact and quick:

result = A(A(:,1)==max(A(:,1)),:)

the inner part A(:,1)==max(A(:,1)), result in a vector of logicals (0 or 1) with each element corresponds to an element in the first column of A, and equals 1 if this element is the largest in the first column of A (i.e. it's max(A(:,1))). In your example it will be [0;0;0;1].

Then, we extract from A each row that has 1 in our logical vector. Note, that if there are several values that are all equal max(A(:,1)) then you'll get all corresponding rows.

Upvotes: 2

informaton
informaton

Reputation: 1482

You can find the row indices for the maximum value of each column of matrix A like this:

[~, maxRowIndicesByColumn] = max(A,[],1);

Then to get the row with the largest value in the first column

A(maxRowIndicesByColumn(1),:)

ans =

 5    20    30

Upvotes: 2

Related Questions