区间累积求和-MATLAB

区间累积求和-MATLAB,matlab,counter,reset,cumsum,Matlab,Counter,Reset,Cumsum,假设我有两个大小相同的输入向量x和reset 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{:

假设我有两个大小相同的输入向量
x
reset

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{:}];

这是因为,如果对第一个输入进行排序,则第二个输入的每组中的顺序将保留下来(更多信息)。

一种方法使用
diff
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)

嘿,它工作得很好,但是你能解释一下这段代码吗。id(reset==1)=diff([0 diff1(reset==1)])@Alex当然,马上就来。非常感谢。“我已经为这件事抓狂了一段时间了。@路易斯门多谢谢,你的也是一个很好的替代方法+1已为您准备好:)