Write a loop that sums and subtracts elements with a lower and upper limit?
Afficher commentaires plus anciens
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 commentaires
JESUS DAVID ARIZA ROYETH
le 11 Nov 2019
What do you mean with the maximum or minimum limit reached?
Walter Roberson
le 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
le 11 Nov 2019
Modifié(e) : Lorenzo Balestra
le 11 Nov 2019
Réponse acceptée
Plus de réponses (1)
KALYAN ACHARJYA
le 11 Nov 2019
Modifié(e) : KALYAN ACHARJYA
le 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 commentaire
Walter Roberson
le 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
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!