sub2ind Get values of 3D matrix using an index vector
5 views (last 30 days)
Show older comments
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,
0 Comments
Accepted Answer
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])
2 Comments
Bruno Luong
on 24 Oct 2018
Alternatively
B = AR(sub2ind([m,n],(1:m)',C(:)),:);
can be replaced by
B = AR((1:m)'+m*(C(:)-1),:)
More Answers (1)
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)
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!