How to extract non-vertical column from matrix in Matlab

后端 未结 2 612
难免孤独
难免孤独 2021-01-24 22:46

I have matrix A and a vector b, which specifies column index of the element to be extracted for each corresponding row of the matrix.

For example,

A = [         


        
相关标签:
2条回答
  • 2021-01-24 23:13

    There may be a more elegant solution, but this works:

    b = [1 3 2]';
    [rows, cols] = size(A);
    A(sub2ind([rows cols], [1 : rows]', b))
    
    0 讨论(0)
  • 2021-01-24 23:17

    As an alternative to @dantswain's solution, you can go to the linear indices directly, assuming you're always selecting from the columns:

    r = size(A,1);
    A( (1:r).' + (b-1) * r)
    

    This will be faster, but not necessarily clearer.

    Unfortunately, there isn't an elegant solution.

    0 讨论(0)
提交回复
热议问题