Loops

Loops allow you to repeatedly execute code.  The two main types of loops that are commonly used include  for and while.  In Matlab, the loop must be completed by the word end.  Through experience you will find that the for loop is useful when the number of iterations that a condition is run is known, whereas a while loop is useful when the number of iterations is unknown.

For Loops

For loops require explicit values in order to function.  These values can be predefined or stated within the loop.
The Matlab syntax is:

for value=start:counter:finish
  [do something]
end

For example:

for i = 1:10
  disp(['Hello I am the number ',int2str(i)]);
end

While loops

While loops will execute code as long as the condition part of the loop is true.  Once false, the loop will stop.  If the value is never true, the loop will never run.  Vice versa, be careful if the condition is always true, as you will entire into an infinite loop.
The Matlab syntax is:

while (condition)
  [perform code]
end
Bookmark and Share