2d matrix of index to get value of 3D matrix

3 views (last 30 days)
heidi pham
heidi pham on 24 Oct 2018
Commented: Stephen23 on 25 Oct 2018
Hello,
I have matrix A with size (37,30,1000); and a matrix B with size (37,1000). I want to use matrix B as a matrix of indexes to get value from A.
The index refers to which column in 3D matrix I want to get the value for each 1st and 3rd dimension.
Is there anyone having an idea how to solve it (prefer not using loop).
Thank you,
  3 Comments
heidi pham
heidi pham on 24 Oct 2018
sorry for my bad expression. I just edited it, hope it clearer now :)

Sign in to comment.

Answers (2)

Bruno Luong
Bruno Luong on 24 Oct 2018
Edited: Bruno Luong on 24 Oct 2018
I'm pretty sure I answered something along this line few days ago
[m,n,p] = size(A);
[I,K] = ndgrid(1:m,1:p);
EXTRACT = A(sub2ind(size(A),I,B,K))
  2 Comments
heidi pham
heidi pham on 24 Oct 2018
thank you, i just tried it and got this error: "Out of range subscript." i've searched arround but could not figure out what exactly caused this error...
Bruno Luong
Bruno Luong on 24 Oct 2018
Edited: Bruno Luong on 24 Oct 2018
Type
min(B(:))
max(B(:))
and verify they are with [1,n] interval, (n=30) in your case.

Sign in to comment.


Matt J
Matt J on 24 Oct 2018
Edited: Matt J on 24 Oct 2018
[m,n,p] = size(A);
idx=reshape(B,m,1,p)==1:n;
result=nan(m,p);
result(any(idx,2))=A(idx);

Community Treasure Hunt

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

Start Hunting!