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

41 views (last 30 days)
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

Accepted Answer

jonas
jonas on 17 Jul 2018
Edited: jonas on 17 Jul 2018
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 Comments
Andy
Andy on 6 Dec 2023
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?

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!