Clear Filters
Clear Filters

Find the cell where the sum equals a threshold

7 views (last 30 days)
Hello,
I have a 32 column by one row array. I want to sum across the values in each column until I match a threshold value. The result should provide the column # (which will be between 1:32)
I've tried a few things and havent been able to iron this down.
Here's the data:
A = [0 0 4520 51418 101386 90907 78735 65863 45766 26831 30586 14864 7905 4741 2840 2475 872 290 99 44 15 2 0 0 0 1 0 2 0 0 0 0];
Threshold value is = 0.5*sum(A).
So I want to find the cell where A = 265081.
The result should provide the cell number (or bin if you will) where this value occurs while summing from the first cell of A to the last.
  1 Comment
Adam Danz
Adam Danz on 8 Aug 2019
"The result should provide the cell number (or bin if you will) where this value occurs while summing from the first cell of A to the last.... So I want to find the cell where A = 265081."
This will never happen with those data. The cumulative sum of A is below and the value 265081 is not a member of that vector.
The best you can do is return the first element that is above or below that value.
cumsum(A)
ans =
Columns 1 through 11
0 0 4520 55938 157324 248231 326966 392829 438595 465426 496012
Columns 12 through 22
510876 518781 523522 526362 528837 529709 529999 530098 530142 530157 530159
Columns 23 through 32
530159 530159 530159 530160 530160 530162 530162 530162 530162 530162

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 8 Aug 2019
Edited: Adam Danz on 8 Aug 2019
Compare the cumulative sum against your threshold. The line below returns the first index of A that is greater than or equal to your threshold.
A = [0 0 4520 51418 101386 90907 78735 65863 45766 26831 30586 14864 7905 4741 2840 2475 872 290 99 44 15 2 0 0 0 1 0 2 0 0 0 0];
threshold = 5000;
idx = find(cumsum(A) >= threshold,1);
If you'd rather have the index of the last element that is less than or equal to your threshold,
idx = find(cumsum(A) <= threshold,1,'last');
  2 Comments
Eric Escoto
Eric Escoto on 8 Aug 2019
Thanks, Adam
The explanation really helps. Yes, in this case I think the first index greater than or equal to would work best. This should trap the value in the index of interest, and return that index.
Much appreciated!
Adam Danz
Adam Danz on 8 Aug 2019
Thanks for the feedback. Be aware if A contains negative values. In that case, the cumulative sum will not be monotonically increasing which may lead to the possibility that you'll have >1 element that passes through your threshold.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!