Azzera filtri
Azzera filtri

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

8 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Star Strider
Star Strider il 30 Gen 2017
Modificato: Star Strider il 30 Gen 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 Commenti
Star Strider
Star Strider il 31 Gen 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.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by