区间累积求和 - MATLAB

Cumulative Summation in intervals - MATLAB

假设我有 2 个大小相同的输入向量 xreset

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

和输出 y,它是 x 中元素的累加和。每当resets的值对应到1时,元素的累加和重新开始,如下图

y = [1 3 6 4 9 15]

我如何在 Matlab 中实现它?

方法如下:

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

这是可行的,因为如果第一个输入 accumarray is sorted, the order within each group of the second input is preserved (more about this here).

diffcumsum -

的一种方法
%// 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)