Borrar filtros
Borrar filtros

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

45 visualizaciones (últimos 30 días)
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

Respuesta aceptada

jonas
jonas el 17 de Jul. de 2018
Editada: jonas el 17 de Jul. de 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 comentarios
Andy
Andy el 6 de Dic. de 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?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by