Sum of an array elements with condition on the sum value

2 ビュー (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by