2015-05-09 110 views
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中實現這一點?

回答

7

一種方法 -

%// 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) 
+0

嘿,它的偉大工程,但你將能夠解釋此部分代碼。 id(reset == 1)= diff([0 diff1(reset == 1)]) – Alex

+0

@Alex好的,來吧。 – Divakar

+0

非常感謝。現在一段時間以來我一直在搔頭。 – Alex

4

這裏有一個辦法:

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

這工作,因爲如果第一個輸入accumarray進行排序,每個組的第二輸入中的順序被保存(更多有關這個here)。

diffcumsum