這個問題與How can I perform this cumulative sum in MATLAB?。相關。MATLAB如何執行滿足兩個條件的cumsum?
是否可以使用TWO條件來執行cumsum?或只是一個條件?
編輯:
data = [1 22 20;... %# Initial data
1 22 22;...
1 22 20;...
1 44 11;...
0 44 12;...
1 33 99;...
1 33 20;...
1 33 50];
我想找到這滿足2個條件累計總和:
% 1) current row in column 1 = 1 && previous row in column 1==1;
% 2) current row in column 2 = previous row in column 2
data(:,4) = cumsum(data(:,3)); % Add a 4th column containing
% the cumulative sum of column 3
index = diff([0;data(:,1)])> 0 && diff([0;data(:,2); 0])~= 0;
offset = cumsum(index.*(data(:,4)-data(:,3)));
data(:,4) = data(:,4)-offset;
index = (data(:,1) == 0);
data(index,4) = data(index,3)
預期輸出:
data = [1 22 20 20 >> 20 + 0
1 22 20 40 >> 20 + 20
1 44 11 84 >> 11 + 40
0 44 12 12 >> 12 + 0
1 33 99 99 >> 99 + 0
1 33 20 119 >> 20 + 99
0 33 50 50 >> 50 + 0
編輯: 用下面的代碼,我得到了錯誤的結果。
index = diff([0;data(:,1)])> 0 & diff([0;data(:,2)])~=0
1 22 20 20
1 22 22 42
1 22 20 62
1 44 11 73 %this supposed to be 11 not 73 ..
0 44 12 12
1 33 99 99
1 33 20 119
1 33 50 169
你的代碼產生了什麼錯誤?如果您不告訴我們,我們會發現(更多)難以診斷您的問題。而你的數據樣本也會有幫助。 – 2010-07-08 08:38:22
???操作數到||和&&運算符必須可以轉換爲邏輯 標量值。 – Jessy 2010-07-08 08:56:15
看起來真的是你想要一種分段累積總和,也就是說,每次第2列的累積和開始變化 - 這是正確的嗎? – 2010-08-16 00:39:03