필터 지우기
필터 지우기

Stop a sum of numbers until a certain value is reached

조회 수: 3 (최근 30일)
Pilar Jiménez
Pilar Jiménez 2019년 10월 21일
댓글: Pilar Jiménez 2019년 10월 22일
If I have defined values
Nmax = 15;
A = [2 5 4 6 1];
I want to make a sum of each value of A in the order in which it is found until it reaches Nmax, if the value is equal to or greater than Nmax the sum stops and the number or numbers that have been pending to be added are saved in another vector B.
How did you get the sum to stop and tell me the index of the vector at which it stopped to be able to save the values forward in the other vector?
Thank you in advance for your help

채택된 답변

Image Analyst
Image Analyst 2019년 10월 21일
You can use cumsum() to do it vectorized, like most MATLABers would:
Nmax = 15;
A = [2 5 4 6 1];
ca = cumsum(A) % Sum them all up
lastIndex = find(ca <= Nmax, 1, 'last') % Last index before the sum would exceed Nmax.
% Show what elements they were "Pending" (whatever that means in this context).
B = A(lastIndex + 1 : end) % The remaining numbers
  댓글 수: 1
Pilar Jiménez
Pilar Jiménez 2019년 10월 22일
Thank you for your help. It really helps me a lot for what I have to do, I've been trying for a long time, I didn't know that the "cumsum" command existed.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Language Support에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by