From: Juliette Salexa on
Hello, I tried:

n=round(7^4.5);
tic;a=rand(n,1);toc;
tic;b=rand(n,n);toc;
tic;sum(b*a);toc;
tic;sum(sum(b));toc;

% Elapsed time is 0.000502 seconds.
% Elapsed time is 3.609380 seconds.
% Elapsed time is 0.161011 seconds.
% Elapsed time is 0.297674 seconds.

-----------------

Which I found strange because the last computation does the same number of summations as the second last, but doesn't have to do any multiplying!

-----------------
For sparse matrices the difference is even bigger:

n=7^6;density=0.001;
tic;a=sprand(n,1,density);toc;
tic;b=sprand(n,n,density);toc;
tic;sum(b*a);toc;
tic;sum(sum(b));toc;

% Elapsed time is 0.049862 seconds.
% Elapsed time is 70.757589 seconds.
% Elapsed time is 0.026991 seconds.
% Elapsed time is 0.206313 seconds.

-----------------

A multiplying AND adding is 10 times faster than just adding ?

Does anyone have any idea why this is true ?