S
- N
x N
sparse matrix.
A
- M
x1 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?
Let's try using find
and accumarray
:
[ii jj sij] = find( S );
x = accumarray( ii, A(sij), [1 size(S,1)] );
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.
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] ).'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.