Loops
This section covers the basics of loops in MATLAB.
Loops in MATLABs typically come in two forms: For-loops and While-loops.
For-loops
For loops iterate over a predetermined set of values (e.g. a counter) and execute a code block as many times as there are elements in the set. The basic syntax of a for loop is the following.
iterator
is a variable that takes on the value of the current element in vector
at which the loop is currently running.
To familiarise yourself with the concept of a for-loop consider the following example.
While-loops
While loops iterate over a code block as long as a boolean condition returns true
.
The basic syntax of a while-loop in MATLAB is the following.
Important: Choose the condition carefully! If the condition never returns true
, the loop will never stop. Therefore it is often good practice to include a counter when using while loops and a conditional statement that stops the iterations if the number of iterations gets too large. The example below presents an example of this.
Example: Finding root of 2 by an easy numeric algorithm
While loops are often used to code algorithms which iterate on a number of steps. Take a look at the following example for an easy numeric algorithm where we try to evaluate when is equal to 2 i.e we wish to find the square root of 2. We will use the following algorithm.
Start at a guess and subtract until we reach the point where up to a tolerance of 1e-2.
To see the danger of while loops, change the tolerance to 1e-3 and run the script again.
Last updated
Was this helpful?