sub2ind Get values of 3D matrix using an index vector

7 Ansichten (letzte 30 Tage)
heidi pham
heidi pham am 24 Okt. 2018
Kommentiert: heidi pham am 24 Okt. 2018
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,

Akzeptierte Antwort

Bruno Luong
Bruno Luong am 24 Okt. 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 Kommentare
Bruno Luong
Bruno Luong am 24 Okt. 2018
Alternatively
B = AR(sub2ind([m,n],(1:m)',C(:)),:);
can be replaced by
B = AR((1:m)'+m*(C(:)-1),:)
heidi pham
heidi pham am 24 Okt. 2018
thank you, it works!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Stephen23
Stephen23 am 24 Okt. 2018
Bearbeitet: Stephen23 am 24 Okt. 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)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by