Vector as column index in matrix

妖精的绣舞 提交于 2019-12-30 11:09:52

问题


Given a matrix A (mxn) and a vector B (mx1) I want to create a vector C (mx1) in which each row element is the row element of A from a column indexed by B.
Is it possible to do this, without using loops?

A = [1 2; 3 4; 5 6];
B = [2 1 1].';

Then I want:

C = [2 3 5].';

回答1:


Convert the column subscripts of B to linear indices and then use them to reference elements in A:

idx = sub2ind(size(A), (1:size(A, 1)).', B);
C = A(idx);

(for more information, read the part about linear indexing in this answer).



来源:https://stackoverflow.com/questions/16508379/vector-as-column-index-in-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!