I have the following situation:
d = [3 39 54 53 6];
n = 103;
What I would like to do is to have a code where: when the sum of the elements in d is bigger than n, then I subtract one from the first column in d that is equal or bigger than n.
In the example above, I would have:
d = [3 39 54 *52* 6];
% since the first column where sum(d) is bigger than n is the fourth column, therefore I subtract 1 from 52
How can I automate this?
Thanks!

 채택된 답변

Rik
Rik 2021년 2월 9일

0 개 추천

Th cumsum and find functions should be useful. Let me know if you have trouble implementing it.

댓글 수: 3

Armando MAROZZI
Armando MAROZZI 2021년 2월 9일
Thanks a lot Rik! I made it, simple and elegant! I don't know why I always get loops first in my head
Rik
Rik 2021년 2월 9일
You're welcome.
Loops are an excellent first step. Matlab is good at optimizing code that is easy to interpret. Loops are the best choice if there isn't a direct function available. Using cellfun (except for the legacy syntax) or arrayfun only hides the loop and tends to have worse performance.
Armando MAROZZI
Armando MAROZZI 2021년 2월 9일
thanks for the tip!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2021년 2월 9일

댓글:

2021년 2월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by