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

10 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2017-1-30
编辑:Star Strider 2017-1-30
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 个评论
Star Strider
Star Strider 2017-1-31
@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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by