How to extract non-vertical column from matrix in Matlab

余生长醉 提交于 2019-12-04 05:28:58

问题


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 = [1 2 3
     4 5 6
     7 8 9]

b = [1 3 2]'

I'd like to have c = [1 6 8]' on output. How to achieve this?

I tried A(:, b), but it doesn't work as I need.


回答1:


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))



回答2:


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.



来源:https://stackoverflow.com/questions/7721240/how-to-extract-non-vertical-column-from-matrix-in-matlab

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