Morteza Rah
Morteza Rah

Reputation: 29

summation of numbers in a vector without loop in matlab

I have a vector with length L. I want to sum each N numbers without a loop in MATLAB for saving time in my simulation.

For example, if L=10 and N=2 for the matrix

A=[1,1,3,3,0,2,4,4,6,2]

the matrix B should be

B=[2,6,2,8,8]

where

B(1)=A(1)+A(2)=2
B(2)=A(3)+A(4)=6

Upvotes: 2

Views: 197

Answers (2)

Xiangrui Li
Xiangrui Li

Reputation: 2426

B = sum(reshape(A, 2, []));

If length of A could be odd number:

n = floor(numel(A)/2) * 2;
B = sum(reshape(A(1:n), 2, []));

Upvotes: 3

Robert Guggenberger
Robert Guggenberger

Reputation: 108

You might also be considering movsum.

C = movsum(A,2);
B = C(2:2:end);

I evaluated its performance to B = sum(reshape(A, 2, [])); Movsum takes roughly 2x the time of reshaping. But it offers some flexibility and runs for non-even length vectors.

Upvotes: 3

Related Questions