Using matrix to index another matrix?
2 次查看(过去 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!