danatel
danatel

Reputation: 4982

Vectorising row lookup

I have a matrix of 1000 rows x 500 columns stored in a. I also have a vector of 1000 integers l in the range between 1 and 500. I want to compute sum of a(i,l(i)) for all i. Can this be done quickly without using for loop?

Upvotes: 1

Views: 71

Answers (2)

rayryeng
rayryeng

Reputation: 104545

Another method I can suggest is to create a sparse matrix that is logical where all values are true such that they are located at the row locations from 1 to N where N is the amount of rows and the column locations directly from using the l vector. You would then use this logical matrix to index into your matrix a then sum up all of the entries. In other words:

s = sparse(1:size(a,1), l, true);
sumval = sum(a(s));

size(a,1) would be N in our case, as this computes the total number of rows. I just decided to place it inside the sparse call to make the code compact.

Upvotes: 2

Divakar
Divakar

Reputation: 221654

You can calculate the linear indices of the elements whose elements are to be summed up and then find the scalar sum value. So, this should do it pretty efficiently -

nrows = size(a,1) %// number of rows in input matrix a
idx = (l(:)-1)*nrows + [1:nrows]' %//'# linear indices of elements to be summed up
                                        %// OR idx = sub2ind(size(a),[1:nrows]',l(:))
sumval = sum(a(idx)) %// index into a and get the sum value

Upvotes: 3

Related Questions