for
a while
¶function [z] = f(x,y,a,b)
z = (x.*x)./(a*a) + (y.*y)/(b*b);
end %function
:+Setup
for
-ever¶In the previous lesson we looked at plotting functions and function handles, and towards the end we started adding multiple plots to the same figure.
To do this, we had to turn hold
on and then type out all the plotting commands that we wanted to execute.
This was fine for us, because we were only plotting 3 different sets of data, but what if you wanted to plot 10 different sets of data?
What about 20?
50? 100? (It happens, trust me.)
Unless you fancy typing out about 100 lines of plot statements, plus another 100-odd lines to actually generate the data that you need to give the plotting commands, you're going to want a alternative method for this.
This is where for
loops come in.
Placing a segment of code in a for
loop (or "for
block") allows it to be executed multiple times using different variable values - ideal for when you have a a process that you want to carry out repeatedly.
Let's look at a minimum informative example:
for i = 1:10
disp(i)
end %for
To tell MATLAB we are starting a for
loop, we of course need to type the keyword for
.
After this keyword, we need to tell MATLAB the values we want to loop over, and give it a "loop" variable - this is what the i = 1:10
part means.
i
is the name that we are giving to our loop variable.
1:10
are the values that we want to loop over; in this case we want i
to take each integer value between 1 and 10 inclusive.
Remember that when slicing arrays, typing 1:10
would mean "take all the values at indices 1 through 10" - it's a similar meaning here.
After the first line, the actual "loop" begins - MATLAB should auto-indent your code to make it clearer for you where the loop begins, but you don't need to do this.
Here we can type commands and use the loop variable i
; in this case our loop consists of only one command - disp(i)
.
To tell MATLAB that the loop is over, we use the end
keyword - yes this is the same keyword as you used to end functions, and will be using to end while
and if
statements too!
As such it's good practice to put a short comment after your end
statements to remind you what they are ending!
When we run the code, you'll notice that each of the values from 1 to 10 are printed to the screen, that is the disp(i)
command has been executed for each value of i
in the range 1:10
, as we asked.
With this idea in mind, let's look at a slightly more illustrative example:
xRange = linspace(0,1,10);
for i = 1:5
vals = f(xRange, 0, i, 1);
disp(vals)
end %for, i
This for
loop has evaluated the function f
(our pringle) over the range xRange
, with y=0,b=1
and a
ranging from 1:5
, and has printed the results to the screen.
Note that we can use variables we define outside a for
loop in the instructions inside the loop, which is handy if there is a variable we use in our process that doesn't change!
Now, consider what happens if we do the following:
xRange = linspace(0,1,250);
varStore = zeros(5,250);
aValues = [0.25 0.5 0.75 1.0 1.25];
for i = 1:5
vals = f(xRange, 0, aValues(i), 1);
varStore(i,:) = vals;
end %for, i
Now we can return to our original question of plotting multiple functions on the same graph: the plan will be to use a for
-loop to generate each set of f
-data, and then add it to a plot.
while
you're at it¶for
-loops provide us with a method of executing similar tasks over and over, whilst changing the variable values or parameters that are being put into the commands themselves.
This is useful when we have a set number of cases to run through, but a for
-loop will (eventually) terminate.
It always has a finite number of cases to run through, and so isn't particularly useful if you want to run some commands until you reach a certain criteria.
For example; you might want to run a numerical method for computing digits of $\pi$ to a certain number of decimal places, or find the roots of a function to a certain tolerance.
The methods here are iterative - they involve "building on" sucessive approximations to a given value of interest.
Using a for
-loop does not guarantee that we will reach the desired level of accuracy - we might not tell our for
-loop to perform enough iterations, or we might go the other way and make it perform too many iterations!
In these cases, it is better to use a while
loop or block.
Code that is placed inside a while
loop will continue to run until a certain condition, provided by the user, is met.
Essentially, a while
loops acts like a for
-loop but doesn't run it's code a fixed number of times.
The general syntax for a while
-loop is:
while <CONDITION>
<PERFORM INSTRUCTIONS>
end %while; yes, this is the same end keyword again...
However an example is more useful:
x = 0;
while x<10
x = 2*x+1;
fprintf('x is now: %d \n', x)
end %while, x<10
fprintf('The value of x at the end of the loop is: %d', x)
In this example, we have a variable x
that begins at the value 0.
The condition on the while
loop is x<10
- this means that all the time x<10
, the loop below will keep running.
Within the loop itself, the first instruction is to double x
and add 1, then to print the new value of x
to the screen.
We can see the result of the loop: x
is set to 1, then 3, 7, and 15.
Upon reaching x=15
, the condition x<10
no longer holds, and so MATLAB moves on from the while loop.
Notice that the value of x
can still be used outside the while
loop, too.