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?
views:
116answers:
2
+3
A:
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
Amro
2010-09-09 04:42:34
Notice, if there are several max values in a column, maxInd will contain only the first occurrence.
yuk
2010-09-09 04:48:28
I try that but keep getting the following error: 'Indexing cannot yield multiple results.'
Jonathan
2010-09-09 04:49:00
also, is i know the specific column the max is, I just need it to give me the row, is there a way for that?
Jonathan
2010-09-09 04:49:42
Try to type `help max`.
yuk
2010-09-09 04:54:44
gave me this: [Y,I] = MAX(X)I tried that and keep getting the same error
Jonathan
2010-09-09 04:56:05
You need this: `[Y,I] = MAX(X,[],DIM)`. If 3rd parameter is 2, you will get max for each row.
yuk
2010-09-09 05:39:36
Edit your question to show a sample of your data and the code you use when you get the error.
yuk
2010-09-09 05:41:08
@Jonathan: it sounds like a variable in your workspace named "max" is masking the "max" function. They share a namespace in Matlab. Do "which max" to confirm this, and if it's the case, "clear" your workspace to fix it. Organizing your code in functions can help prevent this problem.
Andrew Janke
2010-09-09 15:06:06
A:
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)
Jonas
2010-09-09 12:12:12