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

조회 수: 1(최근 30일)
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 2021년 8월 5일
Use sub2ind:
idx = sub2ind(size(A),pnRowsToSelect,pnColsToSelect);
out = A(idx)

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!