Find the cell where the sum equals a threshold

조회 수: 10 (최근 30일)
Eric Escoto
Eric Escoto 2019년 8월 8일
댓글: Adam Danz 2019년 8월 8일
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
Adam Danz
Adam Danz 2019년 8월 8일
"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

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

채택된 답변

Adam Danz
Adam Danz 2019년 8월 8일
편집: Adam Danz 2019년 8월 8일
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
Eric Escoto
Eric Escoto 2019년 8월 8일
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 2019년 8월 8일
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.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by