Get different column in each row

前端 未结 2 950
时光说笑
时光说笑 2021-01-18 05:10

I would like to get a different column out of each row from a matrix. For example:

A = [1,2;1,4;5,2]
B = [2;2;1]

the output should yield:

2条回答
  •  太阳男子
    2021-01-18 05:51

    You can use sub2ind to convert (i,j) indices to linear indices in matrix A

    idx = sub2ind(size(A), 1:size(A, 1), B');
    A(idx)
    
    ans =
    
     2     4     5
    

    That works assuming that vector B has as many entries as there are rows in A. In the above sub2ind generates a linear index for every pair of subsequent row numbers (1:size(A, 1)) and column numbers given in B.

提交回复
热议问题