假设我有2个相同大小的输入向量x
和reset
x = [1 2 3 4 5 6]
reset = [0 0 0 1 0 0]
和输出y
,它是x
中元素的累积和。每当重置的值对应于1时,元素的累积总和将重置并重新开始,如下所示
y = [1 3 6 4 9 15]
我如何在Matlab中实现这个?
答案 0 :(得分:7)
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)
答案 1 :(得分:4)
这是一种方式:
result = accumarray(1+cumsum(reset(:)), x(:), [], @(t) {cumsum(t).'});
result = [result{:}];
这是有效的,因为如果对accumarray
的第一个输入进行排序,则会保留第二个输入的每个组中的顺序(更多关于此here)。