MATLAB Answers

return matrix rows and columns using a one-to-one mapped vector for rows and vector for column

1 ビュー (過去 30 日間)
MatG
MatG 2021 年 8 月 5 日
回答済み: Stephen 2021 年 8 月 5 日
I have a large NxN matrix A. How can I use a column vector pnRowsToSelect = [row1; row2; ...; rowM] and a column vector pnColsToSelect = [col1;col2;...;colM] to return A(row1,col1), A(row2, col2), ..., A(rowM, colM) when row1, row2, ..., rowM can be any rows (not necessarily consecutive) - same for columns. That is "pnRowsToSelect" is the rows whose corresponding columns are "pnColsToSelect" such that the i-th row of "pnRowsToSelect" and i-th row of "pnColsToSelect" is the i-th element of A that I want to return.
For instance, "A= rand(10000);" and "pnRowsToSelect= [ 1; 1000; 4];" and "pnColsToSelect = [ 10 5 100];", then I want to have A(1,10), A(1000, 5), and A(4, 100). I tried "A(pnRowsToSelect, pnColsToSelect)" and this returns A(1,10) , A(1,5), A(1,100) ; A(1000, 10), A(1000, 5), A(1000,100) ; A(4, 10), A(4,5), A(4,100)] whose diagonal element is what I'm looking for. Therefore, I can use "diag(A(pnRowsToSelect, pnColsToSelect))". Is there a more efficientway to do this?

採用された回答

Stephen
Stephen 2021 年 8 月 5 日
Use sub2ind:
idx = sub2ind(size(A),pnRowsToSelect,pnColsToSelect);
out = A(idx)

その他の回答 (0 件)

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by