Sparse matrix multiplication in MATLAB with spfun

2019-08-09 03:05发布

问题:

I have a dense column matrix y of size (m,1) and a sparse matrix x of size (m,n).
I want to do element-wise multiplication using y and every column of x.
The resultant sparse matrix is still of size (m,n).
Sparse matrix x, when loaded into memory, is about 10GB.
Can spfun help me accomplish my goal in a memory efficient manner?

I am having difficulties understanding the logic behind it.

Thank you.

回答1:

Have you tried bsxfun?

out = bsxfun( @times, x, y ); 

spfun is more suitable for element-wise operations where you manipulate each non-zero element of x. It is not exactly fit for matrix-vector element wise operations.
However, if you want to do something along this line, you might try:

[ii jj xij] = find(x); %// extract non-zeros of x and their locations
out = sparse( ii, jj, xij.*y(ii), size(x,1), size(x,2) );

See doc find for more information.