Access all k-th elements of a n-dimensional array, where the k indexes are defined in a (n-1)-dimensional array.

2 次查看(过去 30 天)
I have a 3-dimensional N-by-M-by-L array of values A, e.g.
A(:,:,1) = [1 2 3;
4 5 6;
7 8 9];
A(:,:,2) = [10 11 12;
13 14 15
16 17 18];
I also have a N-by-M matrix containing indexes idx, e.g.
idx = [1 2 1;
2 1 1;
2 2 2];
where the indexes are in the range [1 to L].
I would like to create the N-by-M matrix B such that B(i,j) = A(i,j,idx(i,j)), e.g.
B = [1 11 3;
13 5 6;
16 17 18].
I can see that it could be done easily with nested for loops, but i was wondering if there is a vectorized (and possibly faster) way to achieve this.

采纳的回答

Stephen23
Stephen23 2020-6-2
>> S = size(A);
>> [R,C,~] = ndgrid(1:S(1),1:S(2),1);
>> X = sub2ind(S,R,C,idx);
>> B = A(X)
B =
1 11 3
13 5 6
16 17 18

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by