Borrar filtros
Borrar filtros

How do I index a different column for each row of a matrix without using a loop?

8 visualizaciones (últimos 30 días)
I have a 446,000 x 7 matrix. I have a vector 446,000 specifying the column of interest for each row in the matrix. I.e. from Row 1 I want the second column, from Row 2 I want the 3rd column etc.
How do I extract these values from the matrix without using a loop?
Thanks

Respuesta aceptada

Star Strider
Star Strider el 30 de En. de 2017
Editada: Star Strider el 30 de En. de 2017
One approach:
A = randi(99, 10, 7); % Created Small Matrix
V = randi(7, 10, 1); % Create Similar Vector
idx = bsxfun(@eq, cumsum(ones(size(A)), 2), V);
Result = sum(A.*idx, 2);
  4 comentarios
Star Strider
Star Strider el 30 de En. de 2017
@SeanC — My pleasure.
@John Chilleri — Thank you!
Star Strider
Star Strider el 31 de En. de 2017
@John Chilleri — I appreciate your interest!
I would have left the original, except that I re-read the original post and reconsidered it, since SeanC’s matrix is (446,000x7). My original idea would first create a 198916000000 element square matrix (the reason diag works with it) requiring 1.5913E+012 bytes. At best that’s computationally inefficient, and at most could cause memory problems.
My revised idea transiently duplicates the size of original matrix (in the bit-wise multiplication with the logical matrix), of 24976000 bytes, before ‘collapsing’ it into a vector with the sum call. While I haven’t compared the computation times with the simulated large matrix, I believe it’s more computationally efficient, and certainly more ‘friendly’ with respect to memory usage.

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

Community Treasure Hunt

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

Start Hunting!

Translated by