从另一个向量-matlab创建具有特殊条件和cumsum_function的新向量]

问题描述 投票:1回答:2
考虑一个像'e'的向量。我想在以下条件下进行操作并创建一个新的“ e”矢量。条件:如果e(i)<5,则必须用大于等于5的e(i)+ e(i + 1)替换;否则,必须将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编写

考虑一个像'e'的向量。我想在以下条件下进行操作并创建一个新的“ e”矢量。条件:如果e(i)<5,则必须将其替换为e(i)+ e(i + 1),它必须大于5,否则,则e(i)...

matlab vector manipulate
2个回答
0
投票
如果您想使用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


0
投票
[使用b=cumsum(e)而不是e时,您可以汇总多个成员,只需删除最后一个成员即可。然后最后使用diff
© www.soinside.com 2019 - 2024. All rights reserved.