Writting a loop for calculating difference from previous result of first calculation
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Shahab Khan
am 25 Okt. 2019
Kommentiert: Shahab Khan
am 28 Okt. 2019
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.
0 Kommentare
Akzeptierte Antwort
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
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:
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!