Creating matrix of maximum values from multiple dimension matrix

Asked by Matt on 22 Jul 2012
Latest activity Commented on by Matt on 23 Jul 2012

Given a matrix A, I need to make an array B where each column in B is the maximum value from the corresponding column that maximized the column in A.

Example (2-D):

A=magic(3); A=[8 1 6;3 5 7;4 9 2];

[a,b]=max(A);

a=[8 9 7]; b=[1 3 2];

Since b(2)=3 I need the maximum of A(:,3) to be B(2). So I need to create

B= [8 7 9];

This is simple in two dimensions as I can transpose A and then the index match the rows I need to find the maximum from (B=max(A') works in this case), but in practice I need to do this in multiple dimensions where that approach fails (and therefore B is not a simple row, but is 1xNxP..., differing in each dimension). The first two dimensions are a square which is why they map from rows to columns in this way. Thanks for all ideas.

EDIT: 3D example:

A(:,:,1)= [68 40 71; 76 66 4; 75 18 28] A(:,:,2)=[5 70 4 ; 10 32 44 ; 83 96 39]

[a,b]=max(A);

a(:,:,1) =[76 66 71] a(:,:,2) =[83 96 44]

b(:,:,1) =[2 2 1] b(:,:,2) =[3 3 2]

I want to create

B(:,:,1)=[66 66 76] B(:,:,2)=[44 44 96]

As in A(:,:,1), 66 was the maximum value in column 2 and 76 was the maximum value in column 1.

0 Comments

Matt

Products

No products are associated with this question.

2 Answers

Answer by Andrei Bobrov on 23 Jul 2012
Accepted answer
[a,b]=max(A)
n = size(a);
B = a(sub2ind(n,ones(n),b,repmat(reshape(1:n(3),1,1,[]),1,n(2))));

1 Comment

Matt on 23 Jul 2012

This works for 3D. With a little manipulation this works for ND. Notably, use repmat with square brackets for tiling more than 2 dimensions. I had tried using sub2ind but couldn't get it to work like this. Thanks.

Andrei Bobrov
Answer by James Tursa on 22 Jul 2012
Edited by James Tursa on 22 Jul 2012

Your words don't seem to match your example, at least to me, since you seem to be taking the max of the rows, not the columns. But based on your 2D example, it can be extended to 3D by using permute to do the 3D transpose. E.g.

permute(max(permute(A,[2 1 3])),[2 1 3])

Maybe you could post a 3D example with expected result so we see exactly what you want.

For completeness I will note that mtimesx(1,A,'t') does the same thing as permute(A,[2 1 3]), i.e. take a 3D transpose. MTIMESX can be found in the FEX here:

http://www.mathworks.com/matlabcentral/fileexchange/25977-mtimesx-fast-matrix-multiply-with-multi-dimensional-support

1 Comment

Matt on 22 Jul 2012

I updated with a 3D example for added clarity. When doing [a,b]=max(A), b is the index of the row that maximized each column, so I think it is worded correctly, though perhaps confusing. Apologies if that is still unclear, I cannot think of a better explanation.

This may end up having a better indexing solution than a permutation solution.

James Tursa

Contact us