loop with decrementing step
9 views (last 30 days)
Show older comments
Good Day,
May I ask a question, how can I create loop that the output is like this (10 20 29 38 47 56 65 and so on) and (80 70 61 53 46 40 35 and so on) same in negative (-10 -20 -29 -38 -47 -56 -65 and so on) and (-80 -70 -61 -53 -46 -40 -35 and so on)
The start, end and step is variable
example I can start in 17 to 30 and start step is 5 to 0.125 just like this [17 (+5) 22 until 29.875 (+0.125) 30] same in negation
Accepted Answer
Walter Roberson
on 26 Aug 2021
start = 17;
step = linspace(5,0.125);
stop = 30;
ZZZZZZZZZ_intermediates = start + cumsum([0 step]);
if start <= stop
ZZZZZZZZZ_intermediates = ZZZZZZZZZ_intermediates(ZZZZZZZZZ_intermediates<=stop);
else
ZZZZZZZZZ_intermediates = ZZZZZZZZZ_intermediates(ZZZZZZZZZ_intermediates>=stop);
end
for loop_variable = ZZZZZZZZZ_intermediates
%body of the loop goes here
disp(loop_variable)
end
You might notice that the loop ended before 29.875 . You asked for the increments to be linspace(5,0.125) but remember by default linspace() is a vector of 100 values -- so the first increment would be 5, the second would be about 4.9508, the third is about 4.9501, and so on. Those quickly add up to more than the stop point.
Your requirement to be able to specify an expression for the increments, leads to the possibility that your increments might have a mix of positive and negative numbers. A decision had to be made about what to do for the case where the steps increment past the endpoint but that steps with the opposite sign then take the value back to below the endpoint. Clearly values beyond the end point should not be included... but should you stop as soon as you pass the endpoint the first time, or should you allow for the value to come back?
I decided that since it should be permitted to allow a mix of increments while you are in range, that it would make the most sense to allow values to return back to range. So what I do is filter out the values that go beyond the stop-point -- leaving any that come back to the range. So with positive increments 5 for a while, and negative increments (say) 7, a sequence with start 1 and stop 20 and increments [5 5 5 5 -7 -7] might go [1 6 11 16 (OMITTED 21) 14 7] leaving [1 6 11 16 14 7] as the loop control values.
It might also be reasonable to argue that the sequence should never emit values "before" the start after having gone past it -- so 1:[5 5 5 5 -7 -7 -7]:20 with the logic posted above would give [1 6 11 16 14 7 0] but it would be reasonable to filter on start as well as stop giving loop values [1 6 11 16 14 7] ...
More Answers (0)
See Also
Categories
Find more on Additional Math and Discrete 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!