8
假设我有2输入矢量x
和相同尺寸累积求和 - MATLAB
x = [1 2 3 4 5 6]
reset = [0 0 0 1 0 0]
和输出y
这是在x
元素的累加和的reset
。每当重置的值对应于1,对于元素的累积和复位,从头再来就像下面
y = [1 3 6 4 9 15]
我怎么会在Matlab中实现这一点?
假设我有2输入矢量x
和相同尺寸累积求和 - MATLAB
x = [1 2 3 4 5 6]
reset = [0 0 0 1 0 0]
和输出y
这是在x
元素的累加和的reset
。每当重置的值对应于1,对于元素的累积和复位,从头再来就像下面
y = [1 3 6 4 9 15]
我怎么会在Matlab中实现这一点?
一种方法 -
%// 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)
这里有一个办法:
result = accumarray(1+cumsum(reset(:)), x(:), [], @(t) {cumsum(t).'});
result = [result{:}];
这工作,因为如果第一个输入accumarray
进行排序,每个组的第二输入中的顺序被保存(更多有关这个here)。
diff
和
cumsum
嘿,它的伟大工程,但你将能够解释此部分代码。 id(reset == 1)= diff([0 diff1(reset == 1)]) – Alex
@Alex好的,来吧。 – Divakar
非常感谢。现在一段时间以来我一直在搔头。 – Alex