Index a 3D array with a 2D array of indices
15 views (last 30 days)
Show older comments
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 Comments
Stephen23
on 1 Dec 2017
@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.
Answers (1)
Stephen23
on 2 Dec 2017
Edited: Stephen23
on 2 Dec 2017
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.
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!