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

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.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## KSSV (view profile)

Direct link to this comment:https://nl.mathworks.com/matlabcentral/answers/450854-why-is-manually-adding-elements-of-a-vector-faster-than-passing-a-vector-range-to-sum#comment_682752

## TaipanRex (view profile)

Direct link to this comment:https://nl.mathworks.com/matlabcentral/answers/450854-why-is-manually-adding-elements-of-a-vector-faster-than-passing-a-vector-range-to-sum#comment_682760

## Walter Roberson (view profile)

Direct link to this comment:https://nl.mathworks.com/matlabcentral/answers/450854-why-is-manually-adding-elements-of-a-vector-faster-than-passing-a-vector-range-to-sum#comment_682762

Sign in to comment.