Sum of consecutive groups of array elements

Consider an array

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

Can you then easily add two consecutive numbers to the array together in Matlab so you get:

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

Please note that each item appears in only one amount.

+5
source share
7 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 you play code-golf , vec2mat from Communications System Toolbox can use -

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

Or even more compact -

 B = sum(vec2mat(A,2)') 
+8
source

Try something like:

 B = A(1:2:end)+A(2:2:end) 
+5
source

Yes:

 B = A(1:2:end) + A(2:2:end); 

Best

+5
source

In case the number (A) is not always equal to:

 accumarray(ceil([1:numel(A)]'/2),A(:)) 
+4
source

Here are two other approaches to overall group sizes:

 A = [ 1 2 3 4 5 6 7 8 9 ] groupsize = 2; 

Approach 1

 B = filter( ones(groupsize,1), 1, A ) B = B(groupsize:groupsize:end) 

 B = 3 7 11 15 

Approach 2

 B = conv(A,ones(groupsize,1)) B = B(groupsize:groupsize:end) 

 B = 3 7 11 15 9 

Advantage over Divakar , Ratberts and Jolek is that it also works for vectors A that are not divisible by group size. Keep in mind that both of my approaches in this case are slightly different for the last element.

+2
source

If you assume that A has an even number of elements (xn is even), here is one solution:

  • Extract odd items into a submatrix named odd_arr
  • Extract even elements into a submatrix named even_arr
  • Add two sub-arrays together to make B

Here is the Matlab code (long version):

  odd_arr = A(1:2:end); even_arr = A(2:2:end); B = odd_arr + even_arr; 

Here is the short version:

  B = A(1:2:end) + A(2:2:end); 

I hope this works for you.

0
source

That should do the trick

  B = downsample(A + [A(2:end), 0], 2) 
0
source

Source: https://habr.com/ru/post/1216123/


All Articles