Borrar filtros
Borrar filtros

access the elements in a matrix given the column indexes

5 visualizaciones (últimos 30 días)
zhang
zhang el 15 de Ag. de 2013
For example x = [1 2 3 4; 5 6 7 8; 9 10 11 12]
Given the row indexes vector y = [1 3 4]; I'd like to get the associated elements : x(1, y(1)) = 1, x(2, y(2)) = 7, x(3, y(3)) = 12. [1 7 12]
Don't use loop.
THanks

Respuestas (2)

dpb
dpb el 15 de Ag. de 2013
Editada: dpb el 15 de Ag. de 2013
iy=[1 3 4];
ix=[1:length(iy)];
y=x(sub2ind(size(x),ix',iy');
  2 comentarios
Matt Kindig
Matt Kindig el 15 de Ag. de 2013
I believe that first line is not valid Matlab syntax.
dpb
dpb el 15 de Ag. de 2013
typo, yes...should be obvious. Corrected, thanks.

Iniciar sesión para comentar.


Jan
Jan el 15 de Ag. de 2013
how about
diag( x(:, y) )
  4 comentarios
zhang
zhang el 15 de Ag. de 2013
Yes, you're right. I'm just curious why does this work? can you give a little bit more explanation?
Jan
Jan el 15 de Ag. de 2013
in x(:, y) the colon operator returns all rows of the matrix x. the second argument 'y' does 'column selection', i.e. it picks only the interesting columns from x:
x(:, [1 2 4])
ans =
1 2 4
5 6 8
9 10 12
the values you are looking for obviously appear as diagonal elements in the result and can be extracted with the diag() function.
the reason why the intersting values are on the diagonal is pretty simple, allthough I admit, that one might must give it a second thought :)
I hope that helped!

Iniciar sesión para comentar.

Categorías

Más información sobre Operating on Diagonal Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by