Dante
Dante

Reputation: 796

Index of absolute maximum value of a square matrix in MATLAB

How can I find index of absolute maximum value of a square matrix? for example, consider:

A = 
    1     -2     1
   -3      2    -3
    2     -5     5

MATLAB code should return:

row = 3
col = 2

Note: If there exist more than one element with absolute maximum value, the code should return one of them.

Upvotes: 1

Views: 2025

Answers (3)

user2987828
user2987828

Reputation: 1137

This is easier to read and understand, but will be twice as slow:

[row,col]=find(abs(A)==max(abs(A(:))))

Upvotes: 0

fuesika
fuesika

Reputation: 3330

You can turn the matrix into a vector and determine the position within the matrix from the position within the vector:

B = reshape(A,1,size(A,1)*size(A,2))
[~,I] = max(B)
row = mod(I, size(A,1)
col = floor(I / size(A,2))

Upvotes: 0

Dan
Dan

Reputation: 45741

Use the second output from max on a flattened matrix (i.e. A(:)) and then convert back to subscript indexing using ind2sub. I suggest you read up on linear indexing for a proper understanding of how this works.

A = [1     -2     1
   -3      2    -3
    2     -5     5]

[~,l] = max(abs(A(:)));

[r,c] = ind2sub(size(A),l)

Upvotes: 4

Related Questions