Write a loop that sums and subtracts elements with a lower and upper limit?
Show older comments
Hello,
I have an array that is composed by positive and negative numbers:
P_in_out = [ 1.1 2.2 2.4 3.6 2.4 -3.5 -.6 2 ....]
I have a starting value P and i am addind and subtracting the values
for j = 1 : length (P_in_out)
if j == 1
P_stored(j) = P * 0.5;
else
P_stored(j) = P_stored(j-1) + P_in_out(j);
end
end
The thing i cannot implement is that the value should stop adding values to P_stored once the value lim_max = 500 is reached and should stop subtracting values when the limiti lim_min = 0 is reached.
The loop should not stop when the limit is reached, just stop adding values and write P_stored(j) = lim_max or P_stored(j) = lim_min according to the limit reached.
any idea?
3 Comments
JESUS DAVID ARIZA ROYETH
on 11 Nov 2019
What do you mean with the maximum or minimum limit reached?
Walter Roberson
on 11 Nov 2019
If the value would go from 499 to 501, then should it be not added? Should only as much as needed to reach 500 be added?
Once the limit is reached, is the rule that all further values are to be ignored? Or is the rule that you could add negative values to bring it below 500 again, at which point the next positive value could be added (until the limit) and so on?
Lorenzo Balestra
on 11 Nov 2019
Edited: Lorenzo Balestra
on 11 Nov 2019
Accepted Answer
More Answers (1)
KALYAN ACHARJYA
on 11 Nov 2019
Edited: KALYAN ACHARJYA
on 12 Nov 2019
The thing i cannot implement is that the value should stop adding values to P_stored once the value lim_max = 500 is reached and should stop subtracting values when the limiti lim_min = 0 is reached.
P_stored(1)=P*0.5;
for j=1:length (P_in_out)
P_stored(j) = P_stored(j-1) + P_in_out(j);
if lim_max=>500 || lim_min==0
break
end
end
Is this? you may avoid loop also.
1 Comment
Walter Roberson
on 11 Nov 2019
No, in that code whether lim_max is >= 500 or == 0 is known ahead of time, so it does not make sense to test it in the loop, and lim_min=0 is wrong syntax for an if. You should probably be testing P_stored(i) < lim_min || P_stored(i) >= lim_max
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!