这个问题与如何在 MATLAB 中执行此累积和有关?.
是否可以使用两个条件来执行 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];
我想找到满足两个条件的累积总和:
% 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