How does it work ? For loop

8 views (last 30 days)
David
David on 20 Jan 2023
Answered: Walter Roberson on 20 Jan 2023
I didn’t understand how does this loop work. I know for loop from c language.

Answers (1)

Walter Roberson
Walter Roberson on 20 Jan 2023
In pseudo-code, since MATLAB does not have any GOTO:
for n=4:N
means
test if N < 4
if it is then
assign the empty vector to n
skip the body of the loop
otherwise
copy 4 to _HIDDEN_INTERNAL_VARIABLE_n
copy N to _HIDDEN_INTERNAL_VARIABLE_n_upperbound
Label: _HIDDEN_INTERNAL_LOOP_n
copy _HIDDEN_INTERNAL_VARIABLE_n to n
process the for i at this point (not shown here)
copy _HIDDEN_INTERNAL_VARIABLE_n + 1 to _HIDDEN_INTERNAL_VARIABLE_n_new
test if _HIDDEN_INTERNAL_VARIABLE_n_new > _HIDDEN_INTERNAL_VARIABLE_n_upperbound
if it is then
GOTO _HIDDEN_INTERNAL_LOOP_end_n
otherwise
copy _HIDDEN_INTERNAL_VARIABLE_n_new to _HIDDEN_INTERNAL_VARIABLE_n
GOTO _HIDDEN_INTERNAL_LOOP_n
%end of loop n
Label: _HIDDEN_INTERNAL_LOOP_end_n
Important points:
  • if the endpoint is already greater than the beginning, then the body of the loop is not done at all and the loop control variable is left as []
  • hidden copies of the boundary values are taken before the loop begins, and the hidden copies are what is used. If the variables that were used for the boundary calculations are changed inside the loop, then that does not affect the loop since there is no reliance on those variables once the loop has started
  • the last new value of the variable, the one that would take it over the upper bound, is not written to the loop control variable
  • if the body of the loop (the for i loop in this case) changed the loop control variable, then if there are any remaining iterations, at the beginning of the next iteration, the change will be overwritten with the information stored in the hidden variables
  • if the body of the loop (the for i loop in this case) changed the loop control variable, then if there are no remaining iterations, then after the loop the loop control variable will be left changed. The hidden values do not overwrite the loop control variable until you start a new iteration
I left out details about using increments other than 1, and details about looping backwards (negative increment). I also left out details about what happens if the right hand side of the for statement is : expression, or if it is not a row vector (for example suppose it was 2D on the right hand side of the "for n = ")
Anyhow, that is how a MATLAB for loop works.
... You did not ask anything about the mathematics involved in your loop.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!