Access all k-th elements of a n-dimensional array, where the k indexes are defined in a (n-1)-dimensional array.
3 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Stephen23
on 2 Jun 2020
>> 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 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!