Use values of array as indices for different array

39 ビュー (過去 30 日間)
Thomas Augenstein
Thomas Augenstein 2019 年 5 月 16 日
回答済み: Thomas Augenstein 2019 年 5 月 16 日
I have two matrices, A, B, and C, shown below:
A = [16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1];
B = [1 3
2 3
1 4];
C = [1 3 4];
I want to use the elements of B and C as indices of A to create a new matrix, D, such that each element in C corresponds to a row index in A, and the values in each row of B correspond to column indices given the row index from C. e.g. C(1) = 1 and B(1,:) = [1 3] gives me D(1,:) = A(1,[1 3]). The resulting matrix D would look as follows:
D = [16 3
7 6
4 1];
This is relatively straightforward with a for-loop, but I was hoping for a one-line solution along the lines of A(C,B) = D, which doesn't do what I'm describing in MATLAB. Does anything like what I'm describing exist?

採用された回答

madhan ravi
madhan ravi 2019 年 5 月 16 日
D = A(sub2ind(size(A),repmat(C(:),1,size(B,2)),B))

その他の回答 (1 件)

Thomas Augenstein
Thomas Augenstein 2019 年 5 月 16 日
Great, thank you both!

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by