Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum consecutive groups of elements of an array

Tags:

arrays

matlab

Consider the array

A = [x1,x2,x3,...,xn]

Can you then in an easy way add two consecutive numbers in the array together in Matlab, such that you get:

B = [x1+x2, x3+x4,...]

Note that the each element only appears in one sum.

like image 203
Nicky Mattsson Avatar asked Mar 25 '15 19:03

Nicky Mattsson


People also ask

What is triplet sum in array?

What are triplets in an array? The triplet of an array is a tuple of three elements of different indices, represented by (i, j, k).


1 Answers

With sum and reshape -

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

With interp1 based on this -

nA = numel(A);
start = 1/(2*nA-2);
stop = 1 - start;
B = 2*interp1( linspace(0,1,nA), A,linspace(start,stop,nA/2))

If playing code-golf, vec2mat from Communications System Toolbox could be used -

B = sum(vec2mat(A,2),2)

Or even more compact -

B = sum(vec2mat(A,2)')
like image 68
Divakar Avatar answered Nov 04 '22 18:11

Divakar