ending FOR loop and starting over

1 次查看(过去 30 天)
Hi.
I am building a program where I am summing two values. one is just a number and another is an array
KAP = 5;
n = 1
BAT;
A = [5 10 -5 -7 12 -7 18];
for jj = 1:length(A)
BAT = KAP*n + A(jj)
if BAT < 0
n = n+1
end
end
So i dont know what to do so the value n would increase and also the program should start again at the beggining. So the BAT value is at the end never under 0. Can you help me please i tried with continue and also break and return but still i dont get the right resoult
  1 个评论
Walter Roberson
Walter Roberson 2022-7-12
Do I understand correctly that the desired output is:
  • n = 1 if all A values are non-negative
  • otherwise n = smallest integer such that n*5+A(jj) is non-negative for all jj?
If so then I would suggest to you that in finding n you only need to pay attention to min(A)

请先登录,再进行评论。

采纳的回答

Anay Aggarwal
Anay Aggarwal 2022-7-12
Hi Jernej,
I have an understanding that you want to run the loop for calculating the value of BAT and whenever it is negative then n->n+1 and the loop should start from beginning so that BAT is never under zero at the end of the loop.
As per my understanding, when you are checking for the condition of BAT to be negative, in it you can increase n and redeclare jj=1
KAP = 5;
n = 1
BAT;
A = [5 10 -5 -7 12 -7 18];
for jj = 1:length(A)
BAT = KAP*n + A(jj)
if BAT < 0
n = n+1
jj=1;
end
end
Hope this helps.
Regards
  2 个评论
Bharat Chandra Mukkavalli
Hi Anay,
When you try to update the 'jj' inside the for loop, MATLAB will throw a warning and the value will not be updated.
Please check it once.
Walter Roberson
Walter Roberson 2022-7-13
It is valid to change the for loop variable. However the change will be ignored if any more iterations would normally have occurred.

请先登录,再进行评论。

更多回答(1 个)

Bharat Chandra Mukkavalli
Hi,
I have gone through your code, would you please explain the purpose of the if condition in the for loop?
In the code, the cumulative sum is not being stored and only the value of the n is being updated when the BAT value is less than zero. The final value stored in BAT is KAP*n + A(end).
  1 个评论
Jernej Primozic
Jernej Primozic 2022-7-12
So the hole story is that i have an arrays. i have to go through it and sum it with one preset value. The resoult aways have to be positive. If not i have to increase the number of the preseat value so if n = 1 follows that the KAP = 5
if n is 2 then KAP is 10 and so on
so if i discover that the resoult will not be positive then i have to increase the number (n) and go back and redo it. I hope this explanation is better

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by