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

106 views (last 30 days)
O45 on 7 Feb 2017
Commented: D_coder on 14 Sep 2018
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,

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.
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