Using matrix to index another matrix?

4 vues (au cours des 30 derniers jours)
David Mao
David Mao le 25 Mai 2021
Commenté : David Mao le 26 Mai 2021
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!

Réponse acceptée

James Tursa
James Tursa le 25 Mai 2021
Does this do what you want:
x = sub2ind(size(B),(1:size(A,1))',A(:,1),A(:,2),A(:,3));
Output = B(x);
  1 commentaire
David Mao
David Mao le 26 Mai 2021
Thanks! I used your answer to write this:
x = [size(B), (1:3)', num2cell(A,1)]
Output2 = B(sub2ind(x{:}))

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by