MATLAB Answers

Make a loop in such way that i will be increasing by 5 from 4 up to 30 and by 3 from 30 till up to 50.

1 view (last 30 days)
nty huy
nty huy on 7 Oct 2019
Edited: Rena Berman on 28 Oct 2019
im still confused on using while loops and if loops can someone help me with this question

  2 Comments

Rik
Rik on 7 Oct 2019
It is extremely rude to edit away your question, especially if you received an answer from someone who took the time to read and understand your question and then spent time finding a solution and posting an answer. If you want private help, hire a consultant.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 7 Oct 2019
for VariableName = [4:5:30,30:3:50]
Note that in a case like this, you should always check in case you accidentally repeat a value. For example, [4:13:30, 30:3:50] would start [4, 17, 30] and then continue from [30 33 36 ...] . It so happens that 4:5:30 stops at 29 and so there is no duplication of 30.

  1 Comment

Walter Roberson
Walter Roberson on 7 Oct 2019
for VariableName = [4:5:30,30:3:50]
something
end
is the same as
for VariableName = [4:5:30]
something
end
for VariableName = [30:3:50]
something
end
In turn,
for VARIABLENAME = FIRST_VALUE : INCREMENT : FINALVALUE
something
end
for positive increment is the same as (for your needs, but some of the details differ)
VARIABLENAME = FIRST_VALUE;
while VARIABLE_NAME <= FINALVALUE
something
VARIABLENAME = VARIABLENAME + INCREMENT;
end
So you can simply write two while loops in a row.
However, you can also code something like,
VARIABLENAME = FIRST_VALUE;
first_phase = true;
while VARIABLE_NAME <= FINALVALUE
something
if first_phase
VARIABLENAME = VARIABLENAME + FIRSTINCREMENT;
if VARIABLENAME > BREAKPOINT
VARIABLENAME = BREAKPOINT;
first_phase = false;
end
else
VARIABLENAME = VARIABLENAME + SECONDINCREMENT;
end
end

Sign in to comment.

Sign in to answer this question.

Tags