Create a loop with decrementing step

2 views (last 30 days)
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)
Thanks

Accepted Answer

the cyclist
the cyclist on 25 Aug 2021
Do you mean that you want the increment to be 10, 9, 8, ...? (That is not what your first example does). Here is one way to do a series like that. I hope you can generalize to what you need.
inc = 10:-1:1;
step = cumsum(inc)
step = 1×11
10 19 27 34 40 45 49 52 54 55 55
  6 Comments
Dennis M
Dennis M on 2 Sep 2021
Good Day,
Sir The Cyclist,
Here's my script please check if there's improvement, thanks
clear all
format compact
finalstep = 0.125;
%%
starta = 20;
stopa = 30;
hysa = abs(stopa - starta);
stastep = hysa * 0.2;
stepa = linspace(finalstep,stastep,hysa);
A = stopa - cumsum([0 stepa]);
A = A(A >= starta);
intermediatesa = flipud(A.').';
for loop_variablea = intermediatesa
%body of the loop goes here
a = loop_variablea
end
%%
startb = 15;
stopb = 5;
hysb = abs(stopb - startb);
stastep = hysb * 0.2;
stepb = linspace(finalstep,stastep,hysb);
B = stopb + cumsum([0 stepb]);
B = B( B <= startb);
intermediatesb = flipud(B.').';
for loop_variableb = intermediatesb
%body of the loop goes here
b = loop_variableb
end
%%
startx = -20;
stopx = -30;
hysx = abs(stopx - startx);
stastep = hysx * 0.2;
stepx = linspace(finalstep,stastep,hysx);
X = stopx + cumsum([0 stepx]);
X = X(X <= startx);
intermediatesx = flipud(X.').';
for loop_variablex = intermediatesx
%body of the loop goes here
x = loop_variablex
end
%%
starty = -15;
stopy = -5;
hysy = abs(stopy - starty);
stastep = hysy * 0.2; % start step
stepy = linspace(finalstep,stastep,hysy);
Y = stopy - cumsum([0 stepy]);
Y = Y(Y >= starty);
intermediatesy = flipud(Y.').';
for loop_variabley = intermediatesy
%body of the loop goes here
y = loop_variabley
end

Sign in to comment.

More Answers (0)

Categories

Find more on Model Predictive Control Toolbox 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!