2

consider a vector like 'e'. i wanted to do below conditions and create a new 'e' vector. conditions: If e(i)<5,then it must be replaced with e(i)+e(i+1) that it must be greater than 5,if don't, e(i) must be replaced with e(i)+e(i+1)+e(i+2) and so on. the modified vector can has different length from initial vector.

example:

e(old)=[2,6,10,4,3,6,1,2,3]
e(new)=[8,10,7,6,6]

actually i could write it with this script

    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

but, i want to write it with cumsum_function

amir1122
  • 57
  • 5

2 Answers2

1

If you want to use cumsum, the code below might be a option

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

such that

>> A
A =

    8   10    7    6    6
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0

When using b=cumsum(e) instead of e, you can sum up multiple members, simply by deleting all but the last one. Then at the end you revert to the original representation using 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]);
Daniel
  • 36,610
  • 3
  • 36
  • 69