3

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?

Shai
  • 111,146
  • 38
  • 238
  • 371
IceCube
  • 405
  • 1
  • 5
  • 12

3 Answers3

1

Let's try using find and accumarray:

[ii jj sij] = find( S );
x = accumarray( ii, A(sij), [1 size(S,1)] );
Shai
  • 111,146
  • 38
  • 238
  • 371
0

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.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

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] ).' 
IceCube
  • 405
  • 1
  • 5
  • 12
  • 2
    This is essentially [Shai's answer](http://stackoverflow.com/a/29671739/2586922). You should accept that answer (specially if Shai makes the correction) instead of posting your own – Luis Mendo Apr 16 '15 at 15:22