sub2ind Get values of 3D matrix using an index vector

7 ビュー (過去 30 日間)
heidi pham
heidi pham 2018 年 10 月 24 日
コメント済み: heidi pham 2018 年 10 月 24 日
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,

採用された回答

Bruno Luong
Bruno Luong 2018 年 10 月 24 日
[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 件のコメント
Bruno Luong
Bruno Luong 2018 年 10 月 24 日
Alternatively
B = AR(sub2ind([m,n],(1:m)',C(:)),:);
can be replaced by
B = AR((1:m)'+m*(C(:)-1),:)
heidi pham
heidi pham 2018 年 10 月 24 日
thank you, it works!

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
Stephen23 2018 年 10 月 24 日
編集済み: Stephen23 2018 年 10 月 24 日
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)
  1 件のコメント
heidi pham
heidi pham 2018 年 10 月 24 日
thank you, i will try these ways.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by