Asked by Sanghyun Lee
on 11 Sep 2019

I'm trying to find a way to get the Max value from a 4D array and get the position of each of the max values of the 4D array so that I can trace back and get those positions from another 4D array. It would be great if someone can help me. Thanks in advance!

What I want is to get all the max values of each individual rows and columns and the 3rd dimension and its positions in the 4D.

Answer by Star Strider
on 11 Sep 2019

Try this:

A = rand(3,3,3,3); % Create Array

Amax = max(A(:)); % Maximum Value

Idx = find(A(:) == Amax); % Returns Linear Indices To All ‘Amax’ Values

[r,c,dim3,dim4] = ind2sub(size(A), Idx); % Returns Subscripts In Each Dimension For All ‘Amax’ Values

Sanghyun Lee
on 11 Sep 2019

yeah so the 3rd dimension is 1

oh wait I just realised this.

so is this why it wasn't working before?

Guillaume
on 11 Sep 2019

Don't knoiw what before refers to.

oh wait I just realised this.

Really? you don't know what the size of each dimension is? Then, yes you're going to struggle writing your code if you don't know what is happening with your dimensions.

Sanghyun Lee
on 12 Sep 2019

well no I knew it in my brain but my mind just realised

Sign in to comment.

Answer by Andrei Bobrov
on 12 Sep 2019

Maybe this:

[m,n,k,f] = size(totalDistance);% here k = 1

[~,ij] = max(totalDistance,[],4);

[I,J,K] = ndgrid(1:m,1:n,1:3);

F = repmat(ij,1,1,3);

finalPixels = imagesList(sub2ind([m,n,3,f],I,J,K,F)); % [m,n,3,f] size of imagesList

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Guillaume (view profile)

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/479896-getting-the-max-and-its-positions-from-a-4d-array#comment_744762

## Sanghyun Lee (view profile)

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/479896-getting-the-max-and-its-positions-from-a-4d-array#comment_744765

Sign in to comment.