Igor Tomiatti
Igor Tomiatti

Reputation: 1

Sum each n elements and store in another vector matlab

I have the following function:

b = [-1 1];
m = b(randi(length(b),1,nsimul*n));

Is there a way to do sum to every n elements and store in another vector?

Example:

b = [-1 1];
m = b(randi(length(b),1,5*2));
m
m =
        1    -1     1    -1     1    -1    -1     1     1    -1
A(1) = m(1) + m(2);
A(2) = m(3) + m(4);
A(3) = m(5) + m(6);
A(4) = m(7) + m(8);
A(5) = m(9) + m(10);
A
A = 
        0     0     0     0     0

Upvotes: 0

Views: 134

Answers (2)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

The following code snippet should provide what you are looking for:

% Define the parameters...
nsimul = 5;
n = 2;
b = [-1 1];

% Compute the final result...
m = b(randi(length(b),1,nsimul*n));
k = sum(reshape(m,n,[]).',2);

Given, for example, the vector:

m = [-1 -1  1  1 -1 -1 -1  1  1  1]

The final result s would be:

s = [-2  2 -2  0  2]

with the intermediate result k given by the reshape function equal to:

k = [
 -1  -1
  1   1
 -1  -1
 -1   1
  1   1
]

Upvotes: 0

bla
bla

Reputation: 26069

you can use vec2mat to reshape you vector to a matrix of the dimension that fits the # of elements you want to sum on, and the you just need to sum the right dimension.
vec2mat is nice because it will pad with zeros the reminder of the 1D vector in case you choose a # of elements that is incommensurate with a NxM matrix, For example:

vec2mat(m,2)

ans =

 1    -1
 1    -1
 1    -1
-1     1
 1    -1

more generally, let's call n_elements the # of elements you want to sum on, then:

 n_elements=2;
 a=sum(vec2mat(m,n_elements),2)

But if the 1D vector and the # of elements is always commensurate and no padding is needed you can use the good old reshape, as mentioned in the comments below...

Upvotes: 1

Related Questions