Incremental summation of vector

If A = [1 2 3 4 5 6 7 8 9];
Then how to get B = [A(1)+A(2), A(2)+A(3), A(n-1)+A(n)]; with a single command or short code ??

 Accepted Answer

A = [1 2 3 4 5 6 7 8 9]
A = 1×9
1 2 3 4 5 6 7 8 9
movsum(A,2)
ans = 1×9
1 3 5 7 9 11 13 15 17

2 Comments

Thank you for your answer. I have little concern here, i dont want the starting point (1) of this ans. how to avoid that ?? ans should be directly from 3 5 7 9 11 13 15 17
A = [1 2 3 4 5 6 7 8 9]
A = 1×9
1 2 3 4 5 6 7 8 9
movsum(A, 2, 'Endpoints', 'discard')
ans = 1×8
3 5 7 9 11 13 15 17

Sign in to comment.

More Answers (1)

The + operator can add vectors.
A = 1:10;
B = A(1:end-1)+A(2:end)
B = 1×9
3 5 7 9 11 13 15 17 19

1 Comment

... which is probably the answer expected for the homework ;-)

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!