MATLAB: Sum the component of a vector till a certain value

arrayarrayscell arraycell arrayscodecode generationelseerrorforfor loopif statementMATLABmatlab functionmatlab guimatrixmatrix arrayperformancesumvaluevectorvectors

Hi,
given the vector G= [2 4 4 5 6 16 8 9 21 3 5 8 12 34 5 6 8] I want to obtain a new vector S with the same component but cutted at the element X when the sum of each single elements exceed a specific value Y.
So if in our case Y=80. the new vector S would be
S = [2 4 4 5 6 16 8 9 21 3], in this case the sum of the elements reach 78.
Adding the element 5 we obtain 83, exceeding our limit. That's why we cut at the element X=3, obtaining S= [2 4 4 5 6 16 8 9 21 3].
Does someone know hot to implement this?

Best Answer

G(cumsum(G)<80)