2

考虑像'e'这样的向量。我想做以下条件并创建一个新的“e”向量。条件:如果e(i)<5,则必须替换为e(i)+e(i+1),它必须大于5,否则,e(i)必须替换为e( i)+e(i+1)+e(i+2) 等等。修改后的向量可以具有与初始向量不同的长度。

例子:

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 写它

4

2 回答 2

1

如果你想使用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

这样

>> A
A =

    8   10    7    6    6
于 2020-03-01T22:02:44.660 回答
0

当使用b=cumsum(e)代替时e,您可以总结多个成员,只需删除除最后一个之外的所有成员。然后在最后你恢复到原来的表示使用diff

e=[2,6,10,4,3,6,1,2,3]; %example data
b=cumsum(e);
while true
    ix=find(diff([0,b])<5,1); %find first index violating the rule
    if isempty(ix) %we are done
        break
    end
    b(ix)=[]; %delete element b(ix) to make e(ix)=e(ix)+e(ix+1)
end
e=diff([0,b]);
于 2020-03-01T22:09:13.170 回答