# 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