3
votes

S - NxN sparse matrix.
A - Mx1 vector.

The non zero values of S are the indexes of A.
I want to calculate a vector x such that in the i'th entry of x:
for each non zero value j in the i'th row of S , take A[j] and calculate the sum of all this j's and put it in the i'th entry of x.

in pseudo it should look like this:

  for i = 1:N
     for j = 1:N
        if( s[i][j] != 0)
           x[i] += s[ A[i,j] ]

how can i do it in matlab in the most efficient way?

3
may be there should be another increment? like x[i] += A[s[i][j]]? - Macaronnos

3 Answers

1
votes

Let's try using find and accumarray:

[ii jj sij] = find( S );
x = accumarray( ii, A(sij), [1 size(S,1)] );
0
votes

This is just matrix multiplication:

x = (S~=0)*A(1:size(S,2));

Matlab does matrix multiplication efficiently with sparse matrices, so this should be pretty fast.

0
votes

This is actually like Shai's answer, but uses nonzeros(S) instead sij:

[ii jj] = find( S );
x = accumarray( ii, A(nonzeros(S)), [size(S,1), 1] ).'