示例:
e(old)=[2,6,10,4,3,6,1,2,3]
e(new)=[8,10,7,6,6]
实际上我可以用此脚本编写
clc;clear all
e=[2,6,10,4,3,6,1,2,3];
e_tmp=0;
k=0;
for i=1:size(e,2)
e_tmp=e(i)+e_tmp;
if e_tmp>=5
k=k+1;
A(k)=e_tmp;
e_tmp=0;
else
A(k+1)=e_tmp;
end
end
但是,我想用cumsum_function编写
考虑一个像'e'的向量。我想在以下条件下进行操作并创建一个新的“ e”矢量。条件:如果e(i)<5,则必须将其替换为e(i)+ e(i + 1),它必须大于5,否则,则e(i)...
cumsum
,则下面的代码可能是一个选项e =[2,6,10,4,3,6,1,2,3];
A = [];
while true
if isempty(e)
break;
end
csum = cumsum(e); % cumsum of vector e
ind = find(csum >=5,1,'first'); % find the index of first one that is >= 5
A(end+1) = csum(ind); % put the value to A
e = e(ind+1:end); % update vector from ind+1 to the end
if sum(e) < 5 % if the sum of leftover in e is less than 5, then add them up to the end of A
A(end) = A(end) + sum(e);
end
end
b=cumsum(e)
而不是e
时,您可以汇总多个成员,只需删除最后一个成员即可。然后最后使用diff