Nasty MATLAB performance gotcha

Alec Jacobson

July 16, 2021

weblog/

MATLAB appears to use dense operations when broadcasting certain multiplication/division operations to sparse matrices:

A = sprand(100000,90000,6./100000);
b = rand(size(A,1),1);
spy(A)
tic;C1 = A.*b;toc
Elapsed time is 7.008773 seconds.
tic;C2 = (A'.*b')';toc
Elapsed time is 0.072233 seconds.
norm(C1-C2,inf)
ans =
  0