Filter löschen
Filter löschen

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

8 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Star Strider
Star Strider am 30 Jan. 2017
Bearbeitet: Star Strider am 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 Kommentare
Star Strider
Star Strider am 30 Jan. 2017
@SeanC — My pleasure.
@John Chilleri — Thank you!
Star Strider
Star Strider am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by