【问题标题】:create a new vector with special conditions and cumsum_function from another vector -matlab从另一个向量-matlab 创建一个具有特殊条件和 cumsum_function 的新向量
【发布时间】:2020-06-14 02:58:08
【问题描述】:

考虑像“e”这样的向量。 我想做以下条件并创建一个新的“e”向量。 状况: 如果e(i)

示例:

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

【问题讨论】:

  • 您是否有特定原因要使用cumsum
  • 这是一本 matlab 书中的问题,作者声称它是最紧凑的脚本。@Daniel

标签: matlab vector manipulate


【解决方案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

【讨论】:

    【解决方案2】:

    当使用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]);
    

    【讨论】:

      猜你喜欢
      • 2022-06-28
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 2014-05-24
      • 2012-03-13
      • 2017-09-10
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多