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

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.

 Accepted Answer

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 Comments

Thank you for your answer.
I am having a slight problem here.
These are my actual values.
Initial_value = 48.10;
minimum_value = 12.02;
difference_value = 4.44;
remaining_value = Initial_value;
while remaining_value(end)>minimum_value
remaining_value(end+1) = remaining_value(end)-difference_value;
end
Using the above code I get this output.
43.66 39.22 34.78 30.34 25.90 21.46 17.02 12.58 8.14
I want it to stop by when the remaining value is equal to 12.02 or less than 12.02.
In above case 8.14 is clearly less than 12.02. It should stop at 12.58 but it did not.
"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:
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.

Sign in to comment.

More Answers (0)

Products

Release

R2019b

Community Treasure Hunt

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

Start Hunting!