Creating matrix of maximum values from multiple dimension matrix

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.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 7월 23일
[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

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.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

James Tursa
James Tursa 2012년 7월 22일
편집: James Tursa 2012년 7월 22일
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:

댓글 수: 1

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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2012년 7월 22일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by