how to select an element from each row in a matrix given a vector of column indeces per row (no for loops)

42 次查看(过去 30 天)
Hello, I saw posts to similar questions, but I still couldn't figure out how to do what I want to do. I have a matrix and a vector of values. This vector contains the column indeces to the element I want to extract from each row. for ex:
A=[1 2 3; 3 5 6; 7 8 9];
b = [2 ;1; 1];
I tried x=A(:,b), but this returns
x=A(:,b)
x =
2 1 1
5 3 3
8 7 7
But what I was hoping to get was
x= [2;3;7].
I could do it with a for loop, but is there a different/direct way of doing this?
Thank you, Jorge

采纳的回答

jonas
jonas 2018-7-17
编辑:jonas 2018-7-17
If you want one value from each row, then you could use sub2ind, like this:
A(sub2ind(size(A),1:size(A,1),b'))
This is useful if you have vectors of subscripts (i.e. rows and columns) and you want to extract the corresponding values from a matrix. In this case you want one value per row, so the 2nd argument is just [1 2 3].
  2 个评论
Andy
Andy 2023-12-6
what if there are multiple columns to extract ... A(sub2ind(size(A),1:size(A,1),b')) becomes a complete mess:
A(sub2ind(size(A),repmat(1:size(A,1),1,nrColumns),b'(:)))
Having a matrix MxN, where we need to extract 5 elements from each line, on random column IDs ... isn't there a more elegant than a FOR solution?

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by