Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative Summation in intervals - MATLAB

Suppose I have 2 input vectors x and reset of the same size

x = [1 2 3 4 5 6]
reset = [0 0 0 1 0 0]

and an output y which is the cumulative sum of the elements in x. Whenever the value of resets corresponds to 1, the cumulative sum for the elements reset and start all over again just like below

y = [1 3 6 4 9 15]

How would I implement this in Matlab?

like image 797
Alex Avatar asked May 09 '15 09:05

Alex


People also ask

How do you do a cumulative sum in Matlab?

B = cumsum( A ) returns the cumulative sum of A starting at the beginning of the first array dimension in A whose size does not equal 1. If A is a vector, then cumsum(A) returns a vector containing the cumulative sum of the elements of A .

What does Cumsum in R mean?

The cumulative sum can be defined as the sum of a set of numbers as the sum value grows with the sequence of numbers. cumsum() function in R Language is used to calculate the cumulative sum of the vector passed as argument.

How do you find the sum of a series in Matlab?

Description. F = symsum( f , k , a , b ) returns the sum of the series f with respect to the summation index k from the lower bound a to the upper bound b . If you do not specify k , symsum uses the variable determined by symvar as the summation index. If f is a constant, then the default variable is x .


2 Answers

One approach with diff and cumsum -

%// Setup few arrays: 
cx = cumsum(x)         %// Continuous Cumsumed version
reset_mask = reset==1  %// We want to create a logical array version of 
                       %// reset for use as logical indexing next up

%// Setup ID array of same size as input array and with differences between 
%// cumsumed values of each group placed at places where reset==1, 0s elsewhere
%// The groups are the islands of 0s and bordered at 1s in reset array.
id = zeros(size(reset))
diff_values = x(reset_mask) - cx(reset_mask)
id(reset_mask) = diff([0 diff_values])

%// "Under-compensate" the continuous cumsumed version cx with the 
%// "grouped diffed cumsum version" to get the desired output
y = cx + cumsum(id)
like image 175
Divakar Avatar answered Nov 13 '22 00:11

Divakar


Here's a way:

result = accumarray(1+cumsum(reset(:)), x(:), [], @(t) {cumsum(t).'});
result = [result{:}];

This works because if the first input to accumarray is sorted, the order within each group of the second input is preserved (more about this here).

like image 21
Luis Mendo Avatar answered Nov 13 '22 01:11

Luis Mendo