# Using matrix to index another matrix?

1 ビュー (過去 30 日間)
David Mao 2021 年 5 月 25 日
コメント済み: David Mao 2021 年 5 月 26 日
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!

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

### 採用された回答

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);
##### 1 件のコメント表示非表示 なし
David Mao 2021 年 5 月 26 日
x = [size(B), (1:3)', num2cell(A,1)]
Output2 = B(sub2ind(x{:}))

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

### Community Treasure Hunt

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

Start Hunting!

Translated by