Filter löschen
Filter löschen

Writting a loop for calculating difference from previous result of first calculation

1 Ansicht (letzte 30 Tage)
I have 4 variables.
Initial_value = 50;
minimum_Value = 25;
difference_value = 5;
remaining_value = (Result)
I am trying to write a peice of code which can do following operation automatically:
step 1: Initial_value - difference_value = remaining_value
step 2: remaining_value - difference_value = new_remaining_value
step 3: new_remaining_value - difference_value = new_remaining_value_2
.
.
.
.
last step: loop stops when remaining value is equal to or less than minimum_value
To simplify I setup this example:
step 1: 50 - 5 = 45
step 2: 45 - 5 = 40
step 3: 40 - 5 = 35
step 4: 35 - 5 = 30
step 5: 30 - 5 = 25
End of loop as it reached to 25 (minimum value)
I tried writing this but it only calculates till 1 step.
for i = 100
if remaning_value(i) > minimum_value
a(i) = initial_value(i) - difference_value;
initial_value(i) = remaining_value(i);
end
end
Kindly suggest how shall i acheive this goal.

Akzeptierte Antwort

Stephen23
Stephen23 am 25 Okt. 2019
Initial_value = 50;
minimum_value = 25;
difference_value = 5;
remaining_value = Initial_value;
while remaining_value(end)>minimum_value
remaining_value(end+1) = remaining_value(end)-difference_value;
end
Giving:
remaining_value =
50 45 40 35 30 25
  3 Kommentare
Stephen23
Stephen23 am 26 Okt. 2019
Bearbeitet: Stephen23 am 26 Okt. 2019
"It should stop at 12.58 but it did not."
Think about how while loops actually work: they continue as long as a condition is true and by the time that condition is false, the cause of it being false (e.g. some value being greater than 12.02) has already been calculated and added to your data.
One simple solution is to remove the last element:
while remaining_value(end) >= minimum_value % note: >=
remaining_value(end+1) = remaining_value(end)-difference_value;
end
remaining_value(end+1) = []; % remove last element
See also:
Shahab Khan
Shahab Khan am 28 Okt. 2019
Thanks. I figured it out in while condition I have to use
remaining_value(end+1) = [];
However, this can also be fixed in a better way by using a for loop and if statements.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by