Using matrix to index another matrix?
4 ビュー (過去 30 日間)
古いコメントを表示
Hello, I have an N x 3 matrix that contains indices for an N x 2 x 2 x 2 matrix. An example for N=3:
A = [1 2 2; 2 1 2; 2 2 2] % My indices
B = normrnd(0,1,[3,ones(1,3)*2]) % 3 x 2 x 2 x 2 matrix to be drawn from
Output = zeros(3,1) % Store output in here
for i = 1:3
A2 = num2cell(A(i,:))
B2 = squeeze(B(i,:,:,:))
Output(i) = B2(A2{:})
end
Here, the output is supposed to be a 3x1 vector that takes elements from B depending on the indices given by A. The first element of the output is B(1,1,2,2); the second element is B(2,2,1,2); and the third element is B(3,2,2,2).
The above for loop works, but it is slow. I am trying to do it for N=1000 lots of times, so I am wondering if there is a way to write it without a for loop to make it faster. Thanks so much for taking a look and hopefully there is an easy way to do this!
0 件のコメント
採用された回答
James Tursa
2021 年 5 月 25 日
Does this do what you want:
x = sub2ind(size(B),(1:size(A,1))',A(:,1),A(:,2),A(:,3));
Output = B(x);
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!