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

42 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

jonas
jonas am 17 Jul. 2018
Bearbeitet: jonas am 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 Kommentare
Andy
Andy am 6 Dez. 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?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by