Is there a faster way to multiply a sparse and full matrix than standard multiplication in Matlab?

91 views (last 30 days)
I have a sparse matrix (say A) which has at most 3 to 4 non-zero entries regardless of matrix size. I want to multiply it with a full matrix (Say B) of the same dimension as matrix A.
C = A*B
One way to interpret this product is that each row in C is actually a linear combination of rows of B and the coefficients of the linear combinations comes from rows of A. Since the rows of A has only few (3-4) non-zero entries so it means we only need 3 to 4 rows of B matrix to produce each row of Matrix C. If we can somehow avoid the operations performed by the zero entries and perform the multiplication for many rows in parallel then can we save a implementation time? If yes, I want to know is there any command or any way we can implement this in Matlab?
Thanks,

Accepted Answer

John D'Errico
John D'Errico on 7 Feb 2017
Edited: John D'Errico on 7 Feb 2017
We understand what a matrix multiply means. :) But it sounds like you don't appreciate the use of sparse matrices in MATLAB. Just because your matrix has zero elements in it, does not make it a matrix stored in sparse form.
If your sparse matrix is indeed stored in sparse format, then MATLAB will AUTOMATICALLY use highly efficient multiplication.
A = sprand(1000,1000,0.005);
B = sprand(1000,1000,0.005);
Af = full(A);
Bf = full(B);
whos A B Af Bf
Name Size Bytes Class Attributes
A 1000x1000 87656 double sparse
Af 1000x1000 8000000 double
B 1000x1000 87832 double sparse
Bf 1000x1000 8000000 double
But sparse matrices are not only there to save space. MATLAB does use the known sparsity in a multiplication.
timeit(@() Af*Bf)
ans =
0.078021563737
timeit(@() A*B)
ans =
0.000990737737
If you want something faster than the already fast multiplication built into MATLAB that works with sparse matrices, then, no. Not gonna happen.
  5 Comments
D_coder
D_coder on 14 Sep 2018
what if I want to do element by element multiplication rather than product of two matrices , sparse performs slower than actual multiplication of full matrices
A = sprand(1000,1000,0.005);
B = rand(1000,1000);
Af = full(A);
timeit(@() Af.*B)
ans =
1.8185e-04
timeit(@() A.*B)
ans =
0.0012

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!