Index a 3D array with a 2D array of indices

I have a series of 3D arrays: A, B, C with same dimensions. Data is related between them in the sense that each cell corresponds to a different measurement at the same experiment conditions. With:
[Ma,idx]=max(A,[],3);
M would be a 2D array with the maxima for each vector along the Z axis of the array A. idx would be de indexes along the Z axis vectors that correspond to those maxima.
For the other arrays B,C,D... I would like to obtain 2D arrays Mb, Mc, Md... that would correspond to the same indexes idx along the Z axis of B, C, D...
Is there a vector syntax for that? Or would I have to loop all those arrays along X,Y to index them by the respective element in idx?
B(A==max(A,[],3)
returns the correct elements, but then as a single vector. X/Y dimensions are lost. But I imagine I could make:
idxs = (A==max(A,[],3);
[szx,szy,szz] = size(A);
Mb = reshape(B(idxs), szx, szy);
Mc = reshape(C(idxs), szx, szy);
Md = reshape(D(idxs), szx, szy);
...
Is this an efficient way of dealing with the problem?
Thanks.

댓글 수: 2

Stephen23
Stephen23 2017년 12월 1일
@Edevaldo: I wrote a neat function that resolves this exact problem, but do not have it with me right now. If you wait a few hours I will find a copy and post it for you.
Edevaldo
Edevaldo 2017년 12월 1일
That would be great. Thanks a lot!

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

답변 (1개)

Stephen23
Stephen23 2017년 12월 2일
편집: Stephen23 2017년 12월 2일

0 개 추천

You could download my FEX submission lindex. The function lindex returns linear indices of the correct size corresponding to the subscript indices output by MIN or MAX, and so when you use those linear indices you will get arrays of the correct size. Once you have those indices you can use them repeatedly:
[Ma,idx] = max(A,[],3);
ind = lindex(size(Ma),idx);
%Ma = A(ind) % by definition of LINDEX!
Mb = B(ind)
Mc = C(ind)
...
"... or would I have to loop all those arrays ..." magically accessing variable names is a practice that is best avoided:
so hopefully you only have a few arrays B, C, etc. that you need to perform this operation on. If there are many such arrays then putting them into one larger numeric array or one cell array would make your code and processing much simpler and more reliable.

카테고리

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

질문:

2017년 12월 1일

편집:

2017년 12월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by