sub2ind Get values of 3D matrix using an index vector

5 views (last 30 days)
Dear all,
I have a 37*30*100000 matrix (call matrix A), and a 37*1 vector which contains elements are indexes of the column for each row I want to get the value.
In other word, I want to get a 37*1*1000 matrix (matrix B) from matrix A, using index vector v to get the value corresponding to the column of index specifying by vector v.
Is there anyone having an idea how to work with this, not using for loop (the dimension is very huge!). I think sub2ind might work, but dont know how to adapt it for my situation with 3D matrix.
Thanks,

Accepted Answer

Bruno Luong
Bruno Luong on 24 Oct 2018
[m,n,p] = size(A);
AR = reshape(A,[m*n, p]);
B = AR(sub2ind([m,n],(1:m)',C(:)),:);
B = reshape(B,[m 1 p])

More Answers (1)

Stephen23
Stephen23 on 24 Oct 2018
Edited: Stephen23 on 24 Oct 2018
Given:
A = 37x30x100000 matrix
C = 37x1 vector of column indices
Method one: ndgrid:
S = size(A);
[Rx,~,Px] = ndgrid(1:S(1),1,1:S(3));
Cx = repmat(C(:),[1,1,S(3)]);
X = sub2ind(S,Rx,Cx,Px);
B1 = A(X)
Method two: repmat:
S = size(A);
Rx = repmat((1:S(1)).',[1,1,S(3)]);
Cx = repmat(C(:),[1,1,S(3)]);
Px = repmat(reshape(1:S(3),1,1,[]),[S(1),1,1]);
X = sub2ind(S,Rx,Cx,Px);
B2 = A(X)

Community Treasure Hunt

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

Start Hunting!