Reputation: 27
I'm trying to find a way to find the sets of coordinates of the maximum value/s in a matrix of size [8,8], where the values in the matrix vary from 0 to 6 (generated through the rest of the script/function).
i.e. a matrix of zeros(8,8) where the value 1 is in [3,3], [3,5] and [5,3]. and I want to get returned something along the lines of ([3,3],[3,5],[5,3]) I have tried using things such as ind2sub, etc but with no luck (I keep getting things returned like [I,J] = [ [0,0,3,0,5,0,0,0] , [1,1,1,1,1,1,1,1] ])
Any ideas? If more clarification is needed, just point out where you need it and I'd be glad to do so.
Upvotes: 1
Views: 6446
Reputation: 63451
The problem you've been having with max
so far is because it operates on one dimension. If you call it on a matrix, using its default parameters, it will return a single maximum element (and indices) for each column of the matrix. In your case, you want all maximums, and the global maximum at that.
Try this:
[I,J] = find(M == max(M(:)))
First, max(M(:))
finds the maximum element, then we construct a logical matrix M == max(M(:))
showing which elements are the maximum. Finally, you can use find
to get the co-ordinates of those (if necessary).
Upvotes: 3