Sum of an array elements with condition on the sum value

조회 수: 1 (최근 30일)
Moammer Elzwail
Moammer Elzwail 2019년 11월 30일
편집: dpb 2019년 11월 30일
Hi everybody,
I would like some help here.
So I have a vector (C) that has 10 random numbers.
C = [ 2 5 4 3 6 7 3 4 2 1]. I would like to cumulatively sum the elements with the condition of the sums not exceeding 12 i.e 2+5+4 = 11 (under 12) then move to the next 3+6 = 9 (under 12) .. ans so on. Then storing the cumulaitve sums in a differnt vector G. So the results will be like: G = [11 9 10 7].
Thank you
  댓글 수: 1
dpb
dpb 2019년 11월 30일
편집: dpb 2019년 11월 30일
Probably just the straightforward loop is the simplest here...
You could use cumsum and locate the position via find(cumsum(C)<12,1,'last') and then repeat again with the subsequent portion of the original vector, but I suspect just the straightahead sum will be quicker to code and probably faster.
No really unique solution pops to mind....not to say there isn't one.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by