I'm trying to find the maximum value of a certain column in a matrix. I want to find both the maximum value and the index of the row in which it is. How can I do this?
You can use max() to get the max value. The max function can also return the index of the maximum value in the vector. To get this, assign the result of the call to max to a two element vector instead of just a single variable.
Description. M = max( A ) returns the maximum elements of an array. If A is a vector, then max(A) returns the maximum of A . If A is a matrix, then max(A) is a row vector containing the maximum value of each column of A .
For finding the index of an element in a 3-Dimensional array you can use the syntax [row,col] = find(x) this will give you the row and the column in which the element is present.
Description. k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X . If X is a multidimensional array, then find returns a column vector of the linear indices of the result.
max
command can find both the maximal value and its index.
Here's an example:
>> A = randn(10,3)
A =
0.8884 -0.10224 -0.86365
-1.1471 -0.24145 0.077359
-1.0689 0.31921 -1.2141
-0.8095 0.31286 -1.1135
-2.9443 -0.86488 -0.0068493
1.4384 -0.030051 1.5326
0.32519 -0.16488 -0.76967
-0.75493 0.62771 0.37138
1.3703 1.0933 -0.22558
-1.7115 1.1093 1.1174
>> [maxVal maxInd] = max(A)
maxVal =
1.4384 1.1093 1.5326
maxInd =
6 10 6
If you want the maximum of a specific column, you only pass that column to max
, or you select the column from the resulting list of indices.
%# create an array
A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
%# select the maximum of column 3
[maxValue, rowIdx] = max(A(:,3),[],1)
maxValue =
15
rowIdx =
4
If you need to look up a corresponding value in another array, you use otherArray(rowIdx,3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With