フィルターのクリア

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 Center および File ExchangeLoops 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