O.T.
O.T.

Reputation: 147

How to find the location of the maximum element in a 3D MATLAB matrix?

I have a 3D matlab matrix of size 100*10*1344.

I want to find the three indices of the maximal element of the matrix.

When I try finding it with the command find, I get :

>> [i j k]=find(max(A(:))==A)
i =
    52
j =
    9601
k =
     1

But using these indices gives the following result:

>> A(i ,j, k)
??? Index exceeds matrix dimensions.

How to solve the problem ??

Upvotes: 2

Views: 76

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

You can't have find return three indices, only two. The third output is the value, not an index.

I suggest you get a single index, which will then be a linear index. You can use that directly into A, or convert to three indices with ind2sub.

Example:

A = rand(3,4,5); % example 2D array
ind = find(max(A(:))==A(:));
A(ind) % use linear index directly into A
[ii, jj, kk] = ind2sub(size(A), ind); % or convert to three indices...
A(ii, jj, kk) % ...and use them into A

Also, if you only need the first occurrence of the maximum (in case there are more than one), you can use the second output of max instead of find:

A = rand(3,4,5); % example 2D array
[~, ind] = max(A(:)); % second output of this function gives position of maximum
A(ind) % use linear index directly into A
[ii, jj, kk] = ind2sub(size(A), ind); % or convert to three indices...
A(ii, jj, kk) % ...and use them into A

Upvotes: 6

Related Questions