MATLAB Answers


Why is manually adding elements of a vector faster than passing a vector range to sum()?

Asked by TaipanRex on 19 Mar 2019
Latest activity Answered by Jan
on 19 Mar 2019
>> v1 = [1,2,3,4,5];
>> tic;for i=1:10000000; sum(v1(2:5)); end;toc;
Elapsed time is 1.832466 seconds.
>> tic;for i=1:10000000; v1(2)+v1(3)+v1(4)+v1(5); end;toc;
Elapsed time is 0.446315 seconds.
I am implementing a modified version of Dynamic Time Warping and need to do a lot of summations of parts of vectors, its very slow. As I am doing this moving through a matrix, I can manually do the summation, I have to do a range based on the loop variables, i.e. sum(v1(i:i+5)), which from the example code you can see is much slower. I am also using cumsum() on part of a vector, similarly slow.
Any suggestions of how I can speed this up?


In the first case..yu are calling a function and the function has to pick provided indices....where as int he second case a straight away addition.
Yeah I assumed it was so, so I am trying to find a faster way to do it.
sum([v(1:end-4); v(2:end-3); v(3:end-2); v(4:end-1); v(5:end)])
to do all of them at once.
See also movsum()

Sign in to comment.

1 Answer

Answer by Jan
on 19 Mar 2019

v1(2:5) creates a temporary vector. Some timings looks, like 2:5 is not created, but the indexing is done transparently. Then calling the function sum() costs some time also: The inputs must be parsed - or without inputs, as in your case, default values must be created.
The JIT acceleration is not documented. I assume, the explicite sum can be evaluated more efficiently, because it is less flexible. Maybe some unrolled loops can accelerate the full code, but this is not sure. Some tiny artificial test computations do not reflect the actual efficiency of the computations.


Sign in to comment.