# How do I convert this for loop into a while loop?

1 view (last 30 days)
Jordyn Casados on 15 Sep 2017
Answered: Walter Roberson on 15 Sep 2017
k=zeros(45:1);
for i=1:1:45
k(i)=2*i-2
end

#### 1 Comment

James Tursa on 15 Sep 2017
What have you tried so far? What specific problems are you having with your code?

Walter Roberson on 15 Sep 2017
The general form
for VARIABLE = START : INCREMENT : LAST
%code block goes here
end
can be converted to
hidden_internal_VARIABLE = VARIABLE;
hidden_internal_START = START;
hidden_internal_INCREMENT = INCREMENT;
hidden_internal_LAST = LAST;
IF hidden_internal_INCREMENT == 0
VARIABLE = [];
elseif hidden_internal_INCREMENT > 0
hidden_internal_VARIABLE = hidden_internal_START;
VARIABLE = [];
while hidden_internal_VARIABLE <= hidden_internal_LAST
VARIABLE = hidden_internal_VARIABLE
%code block goes here
hidden_internal_VARIABLE = hidden_internal_VARIABLE + hidden_internal_INCREMENT;
end
else
hidden_internal_VARIABLE = hidden_internal_START;
VARIABLE = [];
while hidden_internal_VARIABLE >= hidden_internal_LAST
VARIABLE = hidden_internal_VARIABLE
%code block goes here
hidden_internal_VARIABLE = hidden_internal_VARIABLE + hidden_internal_INCREMENT;
end
end
where the hidden_internal_ prefixes represent variable names that you can somehow guarantee will not be written by your code block. Considering that your code block might contain eval() or call routines that call assignin() or evalin() or might contain clear or clearvars, this is not something that you can generally guarantee, so in the general case there is no way to mechanically convert between for loops and while loops and retain exactly the same semantics.
For most purposes the conversion is fairly straight forward:
for VARIABLE = START : LAST
%code block
end
is close to being the same as
VARIABLE = START;
while VARIABLE <= LAST
%code block
VARIABLE = VARIABLE + 1;
end
However, this will leave VARIABLE as the value after the last valid one, where "for" leaves it at the last valid value. Also, for copies the end point and increment into internal variables so changes to any variables mentioned do not affect the operation. Also, in for loops, if your code block assigns to the the loop control variable then the change is only retained until the end of the loop, after which the loop control variable is assigned the proper next value as if it had not been changed. These last two factors, protection against change in the increment or last value or loop control variable, are the reason I coded in terms of hidden internal variables.