Effacer les filtres
Effacer les filtres

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

8 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Star Strider
Star Strider le 30 Jan 2017
Modifié(e) : Star Strider le 30 Jan 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 commentaires
Star Strider
Star Strider le 30 Jan 2017
@SeanC — My pleasure.
@John Chilleri — Thank you!
Star Strider
Star Strider le 31 Jan 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by