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

3 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Stephen23
Stephen23 am 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by