Chapter 01 - Starting Matlab
Table of Contents
Three Ways ........................................................................................................................ 1
Version .............................................................................................................................. 1
First you'll have to get Matlab.
Three Ways
There are three primary ways in which you can obtain Matlab, they are as follows:
1. Free, as a student, through the university. To do this follow the link http://www.it.umd.edu/techsavings/software.html We strongly recommend this way because it guarantees you your own functioning
copy of Matlab on your own machine.
2. Through the Engineering Department's Virtual Lab. To run Matlab this way, follow the link http://
eit.umd.edu/vcl/. You'll need to install Citrix first according to the directions given.
3. In one of the labs on campus.
Once you've got Matlab running you'll see several windows. The one you need to pay attention to first is
the main one in the middle. This is where you'll enter your commands and get responses.
Just for fun go into this window and type:
2+2
ans =
4
There, your first Matlab calculation!
Version
Versions numbering of Matlab is a bit confusing but basically the labs, the Virtual Lab and the copy you
can download for free is at least Version 2012a. We'll be assuming you have this version or later for the
tutorial and class.
Published with MATLAB® R2014a
1
Chapter 02 - Basic Commands
Table of Contents
Help! ................................................................................................................................. 1
Arithmetic and More ........................................................................................................... 2
Precision and Other Display Stuff .......................................................................................... 3
Here are some basic commands to get you started.
Help!
One of the most useful and useless commands in Matlab is the help command. It is sometimes useful
because it will give you what you want. For example
help sin
SIN
Sine of argument in radians.
SIN(X) is the sine of the elements of X.
See also ASIN, SIND.
Overloaded methods:
codistributed/sin
gpuArray/sin
sym/sin
Reference page in Help browser
doc sin
lets you see that the sin command assumes the argument is in radians and also, under See also tells
you that you might be interested in asin and sind. You can probably guess what they do. That's useful!
On the other hand it's useless because for example
help diff
DIFF Difference and approximate derivative.
DIFF(X), for a vector X, is [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)].
DIFF(X), for a matrix X, is the matrix of row differences,
[X(2:n,:) - X(1:n-1,:)].
DIFF(X), for an N-D array X, is the difference along the first
non-singleton dimension of X.
DIFF(X,N) is the N-th order difference along the first non-singleton
dimension (denote it by DIM). If N >= size(X,DIM), DIFF takes
successive differences along the next non-singleton dimension.
DIFF(X,N,DIM) is the Nth difference function along dimension DIM.
If N >= size(X,DIM), DIFF returns an empty array.
Examples:
h = .001; x = 0:h:pi;
1
Chapter 02 - Basic Commands
diff(sin(x.^2))/h is an approximation to 2*cos(x.^2).*x
diff((1:10).^2) is 3:2:19
If X = [3 7 5
0 9 2]
then diff(X,1,1) is [-3 2 -3], diff(X,1,2) is [4 -2
9 -7],
diff(X,2,2) is the 2nd order difference along the dimension 2, and
diff(X,3,2) is the empty matrix.
See also GRADIENT, SUM, PROD.
Overloaded methods:
gpuArray/diff
fints/diff
umat/diff
sym/diff
iddata/diff
Reference page in Help browser
doc diff
doesn't tell you anything particularly useful about the diff command, which we'll use a lot.
But the help command is always worth a shot, try it before you try anything else
Arithmetic and More
Previously you did 2+2 and no doubt you were suitably impressed. Here are some other calculations to
get you warmed up.
10*20
ans =
200
sqrt(2)
ans =
1.4142
2^7
ans =
128
2
Chapter 02 - Basic Commands
sin(2*pi/7)
ans =
0.7818
log(3)
ans =
1.0986
Notice that results are returned as decimals which means you often get just an approximation as is the case
with sqrt(2) and the sin and log functions.
Also notice that the log function represents the natural logarithm (the help command would tell you
that). Computer scientists and mathematicians differ on notation sometimes and this is one of those places.
If you want Matlab to do base 10 logarithms you must use log10.
Can you figure out what the following commands do? Try them all!
factorial(5)
round(pi*6)
primes(40)
factor(600)
gcd(120,90)
date
Precision and Other Display Stuff
Whenever you are performing mathematical computations on a computer, you must realize that some
rounding of values is necessarily involved. A computer stores each value in a relatively small finite region
of memory. How could you possibly store a value like pi, which has an infinite non-repeating decimal
expansion, in a small space? You can't. So computers will necessarily round messy numbers. Some programming languages round more than others, but calculations in Matlab are handled fairly precisely. What
we mean is that each numerical value is stored using a lot of digits. For example, calculations involving
the constant pi use the value 3.141592653589793 instead of 3.14 or 3.1416.
However, the internal precision of values in Matlab will not always get displayed when Matlab shows you
an answer. Try the following:
pi
ans =
3.1416
This answer might seem like a disappointing level of precision. The good news is that the internal value
really is stored very precisely, but Matlab assumes that most people just don't want to see all of those
3
Chapter 02 - Basic Commands
ugly digits, so the value is rounded before it is displayed. If you really want to see all of the digits in your
answers to computations, try the following:
format long
pi
ans =
3.141592653589793
Aha! There are those digits. If you want to go back to showing fewer digits in Matlab's answers, just use:
format short
Don't forget that values used in computations are always represented internally using full precision, regardless of whether you specify the long or short format. The format command only affects the way the
answer is displayed on the screen.
format compact
This command suppresses extra line feeds and keeps your Matlab output, from then on, more compact and
with no extra spaces between lines. If you want to return it to normal use
format loose
Published with MATLAB® R2014a
4
Chapter 03 - Variables
Table of Contents
Declaring Variables as Values ...............................................................................................
Accessing Stored Values ......................................................................................................
Altering Variables Depending on Themselves ..........................................................................
A Warning About Stored Variables ........................................................................................
Using ans .........................................................................................................................
Clearing the Variable List .....................................................................................................
Semicolons at the end! .........................................................................................................
1
1
2
3
3
4
4
Like most programming languages, Matlab let you use variables to store values.
Declaring Variables as Values
In Matlab you do not need to declare variables or state their types, just jump in and use them. For example,
try the following:
x = 10
x =
10
This will create a variable called x (or re-use the existing one if you've previously assigned a value to x
during this session), storing 10 as its value. You can now use x in any calculation and it will be replaced
with the value 10.
You should know that in Matlab all of your variables are actually storing matrices, not just an individual
number. In the example above, the variable x is really being initialized with a one-by-one matrix that
contains the value 10. This observation will become important later.
Accessing Stored Values
Once you've stored one or more values in variables, you can recall them at any time by using the variable
names. Below is a very simple example of a session where we store some values in variables and then
use the variables later in a calculation:
width = 5
width =
5
length = 10
1
Chapter 03 - Variables
length =
10
area = length * width
area =
50
Of course the three variables (width, length and area) created above can all be used in any subsequent
calculations that we might want to do.
Altering Variables Depending on Themselves
We can also do something that might confuse the math majors at first. Let's first do:
x=7
x =
7
and then
x=x+1
x =
8
Do you see what this does? In mathematics you may think of x=x+1 as an equation, and one with no
solution. however in this context in Matlab it's treated as an assignment. The way it works is that the right
side x+1 is evaluated to get 8 and then this is assigned to the left side x. The result of this line is that x
is now 8. We can even do more:
x=x+2
x =
10
Now x is 10.
x=x/2
2
Chapter 03 - Variables
x =
5
Now x is 5. And so on.
A Warning About Stored Variables
It is easy to forget that a variable contains a value. Later on when we deal with functions you may need to
figure out f(x) and if you've forgotten that x=10 you may get some unexpected results. So pay attention
to the variables you've assigned.
Using ans
By now you must have noticed that when you ask Matlab to do a calculation for you (and you are not
storing the result explicitly in a variable), Matlab responds with something like:
2*5
ans =
10
Conveniently, ans is itself a variable that you can use in subsequent calculations. It simply stores whatever
the result of the most recent calculation was. Here is a simple example of a session in which we make
use of ans
15 * 3 + 4
ans =
49
ans / 7
ans =
7
ans + 9
ans =
16
3
Chapter 03 - Variables
Clearing the Variable List
If you'd like to start from scratch and eliminate all of the variables that you've created, just type the clear
command:
clear
Be sure that you really don't need the values of the variables before you do this!
Semicolons at the end!
Last but absolutely not least, if you put a semicolon at the end of a Matlab command the command is still
executed but nothing is given as ans. For example note the difference between:
a = 3*4
a =
12
and
a = 3*4;
In both cases a is assigned the value 12 but in the second case Matlab doesn't say anything about it. Very
often in Matlab you want something done and you want Matlab to be quiet about it. Notice in all the
following chapters when and why there are semicolons sometimes but not other times. Experiment and see!
Published with MATLAB® R2014a
4
Chapter 04 - Symbolic Variables
Table of Contents
Declaring ...........................................................................................................................
Factoring Polynomials ..........................................................................................................
Using pretty ...................................................................................................................
Expanding ..........................................................................................................................
Simplifying ........................................................................................................................
Do I Have to Declare Symbolic? ...........................................................................................
1
1
2
2
2
3
In the previous section we learned how to create and use Matlab variables for storing numerical values during a Matlab
session. Now we'd like to introduce a different kind of variable called a symbolic variable.
Declaring
These are necessary when the objects we are manipulating are not just numbers but rather expressions
involving mathematical variables. For example, we would like to be able to use Matlab to manipulate a
polynomial like 6*x^2+5*x-4. The variable x that we see in this polynomial is not really a Matlab
variable because it doesn't have a value. Rather it is a symbolic variable that is part of the polynomial we are
going to be working with. In order for Matlab to manipulate mathematical expressions containing variables,
we have to begin by creating these symbolic variables. For example, you could create the symbolic variable
x like this:
syms x
You can create more than one symbolic variable at a time, like this:
syms x y z
Note that it is perfectly okay to declare a variable as symbolic more than once.
Now that we've created the symbolic variable x, Matlab will be able to manipulate mathematical expressions that contain x. Below we'll practice using symbolic variables in several useful ways.
Note: In all of the examples that follow we are going to be using the symbolic variable x. To get the
examples to work, you must first create the symbolic variable as shown above.
Factoring Polynomials
Suppose you are trying to factor the polynomial 32*x^6 - 88*x^5 - 20*x^4 + 110*x^3 +
55*x^2 - 4*x - 4 using Matlab. No problem -- just use the factor function like this:
factor(32*x^6 - 88*x^5 - 20*x^4 + 110*x^3 + 55*x^2 - 4*x - 4)
ans =
(4*x - 1)*(x - 2)^2*(2*x + 1)^3
1
Chapter 04 - Symbolic Variables
Recall that Matlab uses * for multiplication and ^ for exponentiation. Don't forget the * as Matlab will
error if you forget it.
Using pretty
If you don't like seeing the * and the ^ in the output, you can pass the result of a command like factor
into another command called pretty. Here's how that might look:
pretty(factor(32*x^6 - 88*x^5 - 20*x^4 + 110*x^3 + 55*x^2 - 4*x - 4))
2
(4 x - 1) (x - 2)
3
(2 x + 1)
Expanding
The opposite of factoring is expanding. Suppose you have an expression with parentheses like (7*k
+2)*(5*k-3)*(k+7) and you want to multiply it out. You can use the expand function as illustrated
below. Note that we must first make sure k defined symbolically:
syms k
expand((7 * k + 2) * (5 * k - 3) * (k + 7))
ans =
35*k^3 + 234*k^2 - 83*k - 42
Simplifying
You can ask Matlab to try to simplify any mathematical expression. It doesn't always work! But many times
you'll be impressed by how good Matlab is at this. Below are several examples illustrating the simplify
function:
Try inventing other examples of your own!
simplify(3 * x + (x + 4)*(x - 7) + 15)
ans =
x^2 - 13
simplify((3 * x + 4) / (6 * x ^ 2 + 5 * x - 4))
ans =
1/(2*x - 1)
simplify(cos(x * 3)^2 + sin(x * 3)^2)
2
Chapter 04 - Symbolic Variables
ans =
1
simplify(log(x) + log(2 * x))
ans =
log(2*x) + log(x)
Do I Have to Declare Symbolic?
If you ask Matlab to factor a polynomial without first declaring the variables in it as symbolic you will
get an error. This may seem strange but Matlab is just being sure. If you haven't told it what x is, how
should it know what x^2-4 is, for example?
Published with MATLAB® R2014a
3
Chapter 05 - Solving Symbolically
Table of Contents
The Symbolic Approach .......................................................................................................
Solving One Equation Symbolically .......................................................................................
Which Variable to Solve For? ...............................................................................................
Solving a System of Equations Symbolically ...........................................................................
Order of The Variables in the Solution ...................................................................................
1
1
2
2
4
We can ask MATLAB to try to solve equations two different ways. MATLAB can sometimes obtain a symbolic solution by manipulating the symbols in the equation(s) much like you would do with pencil and paper in an introductory
math class. Another way is to find a numerical answer which may be approximate.
The Symbolic Approach
This approach works well for some problems. Unfortunately there is a large class of problems that will
defy attempts to solve them this way. For example try solving (by hand) the equation
ln(x)+x+1=0
It looks easy to solve but it isn't! An equation like this one can be solved using a numerical method which
will yield a very good approximation to the precise answer. The numerical approach usually involves
taking an initial estimate of the correct solution and then repeating some kind of calculation over and over
to gradually improve the estimate.
Solving One Equation Symbolically
Suppose you want to find the solutions to the equation
4*x-5=7
Matlab can solve this with the solve command. First we symbolically define our variable x and then
apply the command. Try this. Note the use of the ==. Matlab is currently undergoing a change to bring it
in line with most computer programming languages. When checking for equality use ==. There are places
where you can still geta way with one equals sign for checking equality but I recommend against it.
syms x
solve (4*x-5==7)
ans =
3
That was easy! MATLAB found both of the solutions. You can also ask MATLAB to solve equations that
involve arbitrary constants. A nice example is to try to find the general solutions to the generalized form
of the quadratic equation a*x^2+b*x+c=0. What do you think the solutions should look like? Let's see
if you're right...
1
Chapter 05 - Solving Symbolically
syms x a b c
solve(a * x ^ 2 + b * x + c == 0)
ans =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
Do those solutions look familiar? You may have to mentally re-arrange them to make them look the way
you're used to seeing them!
Which Variable to Solve For?
How does Matlab know which variable to solve for? It tries to follow common-sense respecting what we
usually solve for. Since the variable x is so common it solves for that one first. Suppose we wished to
solve a*x-x^2=2 for a; we'd have to tell Matlab as follows:
syms a x
solve(a*x-x^2==2,a)
ans =
(x^2 + 2)/x
Solving a System of Equations Symbolically
You can use the solve command for a whole system of equations as well. For example, suppose we are
trying to find the solution to the following system of equations:
3*x+4*y+z-7=1
x-y-15=2
6*x-2*y-5*z+11=3
We can try to use the solve command to do this by feeding it all of the equations at once, separating
them with commas:
syms x y z
solve (3*x+4*y+z-7==1,x-y-15==2,6*x-2*y-5*z+11==3)
ans =
x: [1x1 sym]
y: [1x1 sym]
z: [1x1 sym]
Hmmmm. That output is a bit disappointing! To enable us to see the actual answers conveniently, we can
introduce an intermediate variable that will store the whole "vector" of answers. Then we can view the
values individually. Here's how that might look:
2
Chapter 05 - Solving Symbolically
syms x y z
MyAnswers = solve (3*x+4*y+z-7==1,x-y-15==2,6*x-2*y-5*z+11==3)
MyAnswers =
x: [1x1 sym]
y: [1x1 sym]
z: [1x1 sym]
Now we can ask to see each of the three values individually, as follows:
MyAnswers.x
ans =
26/3
MyAnswers.y
ans =
-25/3
MyAnswers.z
ans =
46/3
Another way to accomplish the same thing is by assigning the value of the computation to a vector comprised of variables like this:
[x y z] = solve (3*x+4*y+z-7==1,x-y-15==2,6*x-2*y-5*z+11==3)
x =
26/3
y =
-25/3
z =
46/3
3
Chapter 05 - Solving Symbolically
Notice that the answers are displayed as fractions rather decimal expansions. Does that surprise you? It
actually makes sense because Matlab solved the equations symbolically. If you solved these equations by
hand, the last operation you would do in calculating z would be to take 185 and divide it by 13. Although
you could try to evaluate this as a decimal why should you? The expression 185/13 is exact. If this were
written as a decimal it would be 14.230769230769230769230769.... We could only write down
an approximation this way and besides -- it looks really hideous!
Order of The Variables in the Solution
The solve command returns a vector with entries in alphabetical order. For example
solve(x+y==0,x-y+2==0)
will return the vector whose first entry is x and whose second entry is y. If you do something like
[y x]=solve(x+y==0,x-y+2==0)
then what happens is that y gets assigned to the x solution and x gets assigned to the y solution. This
is not what you want.
To unconfuse things make sure that your entries in the vector on the left are in alphabetical order! For
example if your variables are dogs and cats then don't do:
[dogs,cats] = ...
instead do
[cats,dogs] = ...
Published with MATLAB® R2014a
4
Chapter 06 - Symbolic Functions
Table of Contents
What is a Function? ............................................................................................................
Symbolic Functions .............................................................................................................
Plugging into Symbolic Functions ..........................................................................................
Solving with Symbolic Functions ...........................................................................................
Factoring Symbolic Functions ...............................................................................................
Lastly ................................................................................................................................
Functions of Several Variables ..............................................................................................
1
1
1
2
3
3
3
What is a Function?
There are two different ways of thinking of functions in calculus and hence in Matlab. One is symbolically
(as a string of symbols) and the other is as a function handle, which is a little more confusing and will be
left for later. These two ways are interchangeable in some contexts and not in others.
Symbolic Functions
To define a symbolic function we proceed as follows. Note that doing this does two things. It makes x
symbolic and it makes f(x) symbolic.
syms f(x);
f(x) = x^4+7*x^2+x+exp(2*x)
f(x) =
x + exp(2*x) + 7*x^2 + x^4
Now we can do some basic things with this function.
Plugging into Symbolic Functions
We can substitute a constant for the symbol x:
f(3)
ans =
exp(6) + 147
or alternately we could plug in a different symbolic variable provided it's defined as such first:
syms t;
1
Chapter 06 - Symbolic Functions
f(t)
ans =
t + exp(2*t) + 7*t^2 + t^4
or even more complicated expressions:
syms s t;
f(2*t+s)
ans =
s + 2*t + exp(2*s + 4*t) + 7*(s + 2*t)^2 + (s + 2*t)^4
Solving with Symbolic Functions
The solve command works with symbolic functions. If we simply plug in the function then solve sets
it equal to 0:
syms f(x);
f(x) = x^2-x-6;
solve(f(x))
ans =
3
-2
Or we can set it equal to something else using == and solve. It is important to understand that with symbolic
expressions not inside single quotes that we must use == rather than =. The truth of the matter is that
Matlab is slowly moving to the more standard computer science practice of doing this but they're not fully
there yet.
solve(f(x)==5)
ans =
(3*5^(1/2))/2 + 1/2
1/2 - (3*5^(1/2))/2
Or
solve(f(x)==2*x+1)
ans =
2
Chapter 06 - Symbolic Functions
37^(1/2)/2 + 3/2
3/2 - 37^(1/2)/2
Factoring Symbolic Functions
We can also factor symbolic functions, which don't need to be polynomials:
syms f(x);
f(x) = x^2+x*sin(x);
factor(f(x))
ans =
x*(x + sin(x))
Lastly
Lastly, we can use simplify, pretty and expand as well.
Functions of Several Variables
Even though this is beyond the scope of the prerequisites of this course it's worth noting that we can also
assign and work with functions of more than one variable, for example:
syms f(x,y);
f(x,y) = x^2+x*y;
and then
f(2,3)
ans =
10
Published with MATLAB® R2014a
3
Chapter 07 - Solving Numerically
Table of Contents
Introduction ........................................................................................................................
Solving an Equation Numerically using fzero .......................................................................
Choosing Well ....................................................................................................................
Using fzero with Symbolic Functions ..................................................................................
1
1
2
2
Introduction
What happens when symbolic approaches don't work? For example consider the fairly simple equation
log(x)+x+1=0. (Remember that Matlab uses log for natural log!) We can try to solve this symbolically
as shown below:
syms x
solve(log(x) + x + 1==0)
ans =
lambertw(0, exp(-1))
Although this answer is ugly and almost certainly nonsensical, it is 100% exact. [By the way, exp(1)
is the constant e=2.7183... The problem with this answer is that unless you are already familiar with
the Lambert W (Omega) function, this ugly formula will not be very useful for you. Even if you do know
what Lambert's W function is, you still have to do more work to figure out what actual numerical value
the above formula represents. Sometimes you just want to see a number, even if it isn't exactly precise!
Solving an Equation Numerically using fzero
Matlab has a collection of tools for finding approximate solutions but we'll focus on just one, that's the
fzero command. The fzero command takes an initial guess that we provide which is close to the
actual solution and it repeatedly applies an algorithm that will obtain a better and better approximation
until successive approximations are within a certain very small built-in tolerance of one another. Let's say
our starting estimate is the value 2. We could call fzero like this:
syms x
fzero('log(x) + x + 1', 2)
ans =
0.2785
What this has done is find a root which is close to our initial guess of 2.
1
Chapter 07 - Solving Numerically
Choosing Well
It's important to give fzero a good initial guess. For example the equation sin(1/x)=0 has many
solutions but only one of them near 0.3. If we do
fzero('sin(1/x)',0.1)
ans =
0.1061
we don't get the one we want because 0.1 is not near the one we want. Instead we have to start close
to the one we want.
fzero('sin(1/x)',0.3)
ans =
0.3183
Using fzero with Symbolic Functions
If you try the following you'll get an error:
syms f(x);
f(x) = sin(1/x);
fzero(f(x),0.3)
Error using fzero (line 169)
If FUN is a MATLAB object, it must have an feval method.
Error in Ch07_SolvingNumerically (line 63)
fzero(f(x),0.3)
The reason for this is that the fzero method can't handle symbolic functions. Don't ask me why, personally I consider it a flaw in Matlab. In any case in general fzero can only handle symbolic expressions
contained in single quotes or function handles, which were briefly mentioned before and will be revisted
shortly.
Published with MATLAB® R2014a
2
Chapter 08 - Script M-Files
Table of Contents
What is a Script M-File? ...................................................................................................... 1
A Simple Script M-File ........................................................................................................ 1
A Note about Script M-Files ................................................................................................. 3
What is a Script M-File?
Before we proceed further consider that when you're writing a Matlab project which involves typing a
bunch of commands you probably don't want to type them over and over. In other words it would be
helpful to create a "project" which contained all the commands you wished to execute. This would also be
convenient for handing in homework assignments (hint hint!) Script M-files allow us to do this. Simpler
than the function M-files we'll look at later, script M-files are just text files with a .m extension which
contain Matlab code that you want to run.
A Simple Script M-File
Suppose you want to write a series of commands to demonstrate your fantastic Matlab knowledge. You
wish to put those in a file and then turn it in to your teacher. Simple! First create your first script. The
following can be done either from within Matlab (which will open its own editor for you) or with any
text editor you prefer.
edit firstscript.m
In this file type the following. This is simply a giant collection of a bunch of commands you've already
learned. Nothing will happen as you type these into the file, they'll just sit there.
3+5
sqrt(10)
gcd(120,90)
date
format long
1/7
format short
1/7
x=3.1
x^2
syms t
factor (t^3-5*t^2-6*t)
syms f(t)
f(t) = t^3+2*t^2
f(3)
f(t+2)
solve(f(t)==3*t)
simplify(f(t)*f(t))
expand(f(t)*f(t))
pretty(f(t)^3)
1
Chapter 08 - Script M-Files
Save this file. Now the file is available and as long as it is available you can run those lines of code simply
by typing the following into Matlab.
firstscript
ans =
8
ans =
3.1623
ans =
30
ans =
02-Sep-2014
ans =
0.142857142857143
ans =
0.1429
x =
3.1000
ans =
9.6100
ans =
t*(t + 1)*(t - 6)
f(t) =
t^3 + 2*t^2
2
Chapter 08 - Script M-Files
ans =
45
ans =
2*(t + 2)^2 + (t + 2)^3
ans =
0
1
-3
ans =
t^4*(t + 2)^2
ans =
t^6 + 4*t^5 + 4*t^4
3
(t
2 3
+ 2 t )
Note: When you run your script do not add the .m extension! If you do the script will run but then you'll
get a peculiar error.
A Note about Script M-Files
Just for the record, script M-files do not take parameters and do not return values. They simply contain
lists of commands which are executed sequentially. For this reason they're perfect for doing a homework
assignment which will be handed in. Moreover as we'll see in a subsequent lesson, M-files can be published to create html code which contain the commands and all the output (including graphs!) as well as
comments. That's coming up shortly!
Published with MATLAB® R2014a
3
Chapter 09 - Plotting Curves
Table of Contents
Using ezplot ...................................................................................................................
Changing the Window Domain ..............................................................................................
Equations ...........................................................................................................................
An Alternate Command .......................................................................................................
1
2
4
5
Using ezplot
A picture is worth 1000 words. Let's learn how to get Matlab to show us some graphs. The easiest way is
to use a command called ezplot. Suppose you want to draw the graph of the function f(x)=sin(x)
over the interval from -pi to pi. Try typing the following command:
syms x
ezplot(sin(x))
This will also work with a symbolic functon:
syms f(x)
1
Chapter 09 - Plotting Curves
f(x) = cos(1/x);
ezplot(f(x))
Changing the Window Domain
Matlab tries to make a reasonable choice of how much of the function to show. It often gives quite a good
result. If you prefer you can tell it what domain to plot.
ezplot(sin(x), [0, 20*pi])
2
Chapter 09 - Plotting Curves
How about this one:
ezplot(sin(1/x), [0, 0.1])
3
Chapter 09 - Plotting Curves
Equations
Just so you know, ezplot can do equations, too.
syms x y
ezplot('x^2+4*y^2=16')
4
Chapter 09 - Plotting Curves
An Alternate Command
There is an alternative function called plot that gives you much more flexibility and options with your
graphs, but it is a bit more advanced. If you'd like to learn about plot, try reading the Matlab help entry.
For now, ezplot is all we'll need.
Published with MATLAB® R2014a
5
Chapter 10 - Differentiation
Table of Contents
Using diff .......................................................................................................................
Higher Derivatives ..............................................................................................................
IMPORTANT .....................................................................................................................
Higher Derivatives - An Alternate Way ..................................................................................
A Different Variable ............................................................................................................
Wait, that Second Parameter? ................................................................................................
Again with Symbolic Functions .............................................................................................
Differentiating and then Plugging In - Using subs. ..................................................................
Plotting Derivatives .............................................................................................................
1
1
2
2
2
3
3
3
4
Differentiation is the most important thing in calculus so let's get to it!
Using diff
What about calculus? Don't worry -- Matlab will not let you down! Suppose you'd like to differentiate
the function log(6*x+2). You could either do it yourself or... just ask Matlab to do it with the diff
command:
syms x
diff(log(6 * x + 2))
ans =
6/(6*x + 2)
Or with a symbolic function:
syms f(x);
f(x) = cos(x^2+2*tan(x));
diff(f(x))
ans =
-sin(2*tan(x) + x^2)*(2*x + 2*tan(x)^2 + 2)
Higher Derivatives
What could be easier?
Would you like to find the third derivative of the function log(6*x+2)? That's easy too -- just pass 3
as a second parameter to the diff command:
diff(log(6 * x + 2), 3)
1
Chapter 10 - Differentiation
ans =
432/(6*x + 2)^3
IMPORTANT
It is a common mistake to believe that the 3 in the above calculation will take the first derivative and plug
in x=3. It does not do this! If you want to differentiate and then plug in just wait a bit and we'll cover that.
Higher Derivatives - An Alternate Way
It's worth noting that we could have taken the third derivative this way, though we probably wouldn't:
diff(diff(diff(log(6*x+2))))
ans =
432/(6*x + 2)^3
A Different Variable
Suppose our expression has two variables and we want the derivative with respect to one of them. As
usual x is the default
syms a x
diff(a^3*x^4)
ans =
4*a^3*x^3
but we can tell Matlab differently.
diff(a^3*x^4,a)
ans =
3*a^2*x^4
We can even do the second derivative with respect to a.
diff(a^3*x^4,a,2)
ans =
2
Chapter 10 - Differentiation
6*a*x^4
Wait, that Second Parameter?
Matlab is smart. If the second parameter is a variable it will take the derivative with respect to that variable.
If it's a number it will take that numbered derivative. If it sees a variable and then a number it will take
that numbered derivative with respect to that variable.
Again with Symbolic Functions
If we have a symbolic function of multiple variables we can differentiate too:
syms f(x,y);
f(x,y) = 2*x^2*y^3+x*sin(x*y);
diff(f(x,y),x)
ans =
sin(x*y) + 4*x*y^3 + x*y*cos(x*y)
We could even take the deriative with respect to x and then with respect to y. This might only make sense
to those with multidimensional calculus:
diff(diff(f(x,y),x),y)
ans =
2*x*cos(x*y) + 12*x*y^2 - x^2*y*sin(x*y)
Differentiating and then Plugging In - Using
subs.
It may seem a bit late but this is the perfect time to talk about plugging things into symbolic expressions.
Here's how. Suppose we simply want to plug x=3 into x^2-x+2. We do:
subs(x^2-x+2,x,3)
ans =
8
So now to take the derivative and then plug in, we simply nest the commands. Here's the second derivative
of x^3+exp(x^2) with x=1 plugged in:
subs(diff(x^3+exp(x^2),2),x,1)
3
Chapter 10 - Differentiation
ans =
6*exp(1) + 6
Or with a function:
syms f(x);
f(x) = 1/(x^2+3);
subs(diff(f(x)),x,-3)
ans =
1/24
Plotting Derivatives
Likewise we can nest diff inside ezplot. Here's an example, a plot of the derivative of sin(x^2):
ezplot(diff(sin(x^2)))
Published with MATLAB® R2014a
4
Chapter 11 - Integration
Table of Contents
Indefinite Integrals ..............................................................................................................
With Symbolic Functions .....................................................................................................
Where's the +C? .................................................................................................................
Definite Integrals ................................................................................................................
Approximating Integrals .......................................................................................................
1
1
1
1
2
Integration can be indefinite or definite. Matlab can do both. If the definite integration is too tricky or impossible,
Matlab can approximate.
Indefinite Integrals
Suppose you'd like to integrate the function 7/(1+x^2). Hmmm.... that reminds me of something I've
seen before, but I can't recall the formula... Something about an inverse trig function... Ah, let's just ask
Matlab:
int(7/(1 + x^2))
ans =
7*atan(x)
That's it! Matlab uses atan for arctangent which is the same as inverse tangent.
With Symbolic Functions
We can do the same with symbolic functions:
syms f(x);
f(x) = x^3-x*log(x);
int(f(x))
ans =
(x^2*(x^2 - 2*log(x) + 1))/4
Where's the +C?
Matlab doesn't put the +C, which I find odd since it does for differential equations as we'll see later.
Definite Integrals
Suppose we'd like to compute the area under the curve f(x) = x^3 + ln x over the interval where
x is between 5 and 10. Just pass those end-points to the int command as two additional parameters:
1
Chapter 11 - Integration
int(x^3+log(x),5,10)
ans =
5*log(20) + 9355/4
Approximating Integrals
We've seen how the int command can be used to find definite integrals. You should know that int does
its job using symbolic integration techniques, similar to the ones you would use if you were integrating
something with paper and pencil in a first semester calculus course. Unfortunately, there are many functions that are difficult or impossible to integrate this way since no nice antiderivative exists. For example:
int(sqrt(sin(x).*5), 1, 2)
ans =
-2*5^(1/2)*(ellipticE(pi/4 - 1, 2) - ellipticE(pi/4 - 1/2, 2))
That answer is not really what we were after - We just wanted a number! What in the world is ellipticE
anyway?! In order to apply some numerical integration techniques and get approximations we'll need to
wait until we have function handles later.
Published with MATLAB® R2014a
2
Chapter 12 - Solving
Differential Equations
Table of Contents
Introduction ........................................................................................................................
Having No Independent Variable. ..........................................................................................
Initial Value Problems .........................................................................................................
With Symbolic Functions .....................................................................................................
Plotting a solution. ..............................................................................................................
Compound Example ............................................................................................................
An Example with Variables ..................................................................................................
1
1
2
2
3
4
4
Introduction
Matlab is quite powerful when it comes to solving differential equations. The standard command is dsolve
(think Differential Solve) and has the format dsolve('equation','variable'). Here equation
is a differential equation in the form of a string and variable is the independent variable. For example
suppose we wished to solve y'=2y+x.
We can type this into Matlab as:
dsolve('Dy=2*y+x')
ans =
(C5*exp(2*t))/2 - x/2
Note that Dy represents the derivative of the variable y. Also we should note here that you may get a
differently numbered constant C1, C2, etc. depending upon how many constants that have shown up in
Matlab for you. Don't worry for now about how they're numbered.
Having No Independent Variable.
Consider the differential equation y'=3y. If you do this in Matlab:
dsolve('Dy=3*y')
ans =
C7*exp(3*t)
You see the solution is given as a function of t. Why t? The answer is that first, the differential equation
has no independent variable so Matlab doesn't know what y is supposed to be a function of. Second, t is
1
Chapter 12 - Solving
Differential Equations
pretty normal since often differential equations are used for functions of time. If you want another variable
you can tell Matlab:
dsolve('Dy=3*y','x')
ans =
C9*exp(3*x)
We can use higher derivatives like D2y and D3y too. For example we can solve y''=2y treating y as
a function of z by typing:
dsolve('D2y=2*y','z')
ans =
C11*exp(2^(1/2)*z) + C12*exp(-2^(1/2)*z)
Initial Value Problems
We can also state initial conditions using the form dsolve('equation','initial
condition','variable') where initial condition is also a string. For example:
dsolve('Dy=2*y','y(0)=5','x')
ans =
5*exp(2*x)
And higher order with multiple initial conditions:
dsolve('D2y+Dy=x','y(0)=1,Dy(1)=2','x')
ans =
2*exp(1) - x - 2*exp(-x)*exp(1) + x^2/2 + 1
Matlab can of course do much more with differential equations as we'll see but for now just appreciate
that it can handle most straightfoward examples with no problem at all.
With Symbolic Functions
We may also solve differential equations that contain a function defined symbolically. The notation is
quite different so be very careful! Consider the following example which solves the differential equation
y'=y+t:
syms y(t);
2
Chapter 12 - Solving
Differential Equations
dsolve(diff(y,1)==y+t)
ans =
C20*exp(t) - t - 1
Here is the same differential equation with an initial value. Make sure you use == in these cases and notice
the lack of single quotes.
dsolve(diff(y,1)==y+t,y(1)==-2)
ans =
- t - 1
It is important to note that we've written y and not y(t) here. If you write y(t) this will error.
Plotting a solution.
Plotting a solution is as easy as wrapping dsolve in ezplot:
ezplot(dsolve('Dy=0.05*(500-y)','y(0)=10','t'),[0,100])
3
Chapter 12 - Solving
Differential Equations
Compound Example
Here's an example of a single Matlab line which will solve the initial value problem y'+3y+10=0 with
y(1)=2, set the result equal to 0 and solve for x. Note that both the 'x' are not necessary since there's
only one independent variable.
solve(dsolve('Dy+3*y+10=0','y(1)=2','x'),'x')
ans =
-log((5*exp(-3))/8)/3
Here's the same thing with a symbolic function:
syms y(t);
solve(dsolve(diff(y)+3*y+10==0,y(1)==2))
ans =
-log((5*exp(-3))/8)/3
An Example with Variables
You may notice that if you try the following:
a=2;b=3;
dsolve('Dy=a*x+b','x')
ans =
(a*x^2)/2 + b*x + C31
This is annoying. You wanted a and b to be in the answer! The point is that 'Dy=a*x+b' is treated as
a string of characters and therefore a and b as just letters. They're not given their values. To get around
this you can solve and then substitute:
clear all;
subs(dsolve('Dy=a*x+b','x'),{'a','b'},{2,3})
ans =
x^2 + 3*x + C2
Or if you use a symbolic function then the lack of single quotes makes Matlab automatically use the a
and b you assigned:
clear all;
4
Chapter 12 - Solving
Differential Equations
syms y(t);
a=2;b=3;
dsolve(diff(y)==a*t+b)
ans =
C2 + t*(t + 3)
Published with MATLAB® R2014a
5
Chapter 13 - Function Handles
Table of Contents
........................................................................................................................................
Function Handles ................................................................................................................
Differentiation and Integration ...............................................................................................
Numerical Integration of Function Handles ..............................................................................
The matlabFunction Command .......................................................................................
Plotting Function Handles .....................................................................................................
More Complicated Calculations - IMPORTANT! .....................................................................
1
1
2
3
3
4
4
So far we have seen functions defined symbolically. Matlab also has functions which are defined as function handles. These are used for certain Matlab commands like quad and fzero and are also used when
we need to pass functions to function m-files as arguments as we will do in the last chapter.
Function Handles
Function handles are defined using the @ operator. Consider the following example:
f = @(x) x^5-3*x
f =
@(x)x^5-3*x
This tells Matlab to create a function for which x is the variable (this is what the @(x) does) and for which
the rule is x^2-x. Here are some things we can do with function handles. We can plug things in:
f(3)
ans =
234
We can use fzero to approximate a root:
fzero(f,2)
ans =
1.3161
1
Chapter 13 - Function Handles
Differentiation and Integration
Differentiating is a bit obscure. We cannot simply do diff(f) because diff doesn't work as-is on
function handles. However if we define x as symbolic then Matlab will accept diff. What's happening
here is that f is a function handle but f(x) is symbolic because symbolic x is plugged in:
clear all;
f = @(x) x^5-3*x;
syms x;
diff(f(x))
ans =
5*x^4 - 3
and
diff(f(x),2)
ans =
20*x^3
Also, strangely, provided x is symbolically defined then the following will work:
diff(f,x,2)
ans =
20*x^3
Integration works the same way in that int(f) and int(f,1,2) will not work but provided x is
symbolic:
clear all;
f = @(x) x^5-3*x;
syms x;
int(f(x))
ans =
(x^2*(x^4 - 9))/6
and
int(f(x),1,2)
2
Chapter 13 - Function Handles
ans =
6
will work fine, as will:
int(f,x,1,2)
ans =
6
Numerical Integration of Function Handles
Now that we have function handles we can use integral to do numerical integration. However there's
another caveat. The Matlab integral command does its work with vectors and consequently for reasons
we will not go into right now we must replace * and / and ^ with .* and ./ and .^. For example:
clear all;
f = @(x) exp(x.^2);
integral(f,1,2)
ans =
14.9900
The matlabFunction Command
If you're confused or frustrated there is a command, matlabFunction (notice the weird capitalization)
which converts symbolic functions into function handles. The following might be prettier to you:
clear all;
syms f(x);
f(x) = exp(x^2);
integral(matlabFunction(f(x)),1,2)
ans =
14.9900
Lastly the function handle can just be plugged directly in, for example:
clear all;
integral(@(x) sin(x.^2),1,2)
ans =
3
Chapter 13 - Function Handles
0.4945
Plotting Function Handles
The ezplot command however works fine other than a warning:
clear all;
f = @(x) cos(x)^2;
ezplot(f,[-pi,pi])
Warning: Function failed to evaluate on array inputs; vectorizing the funct
may speed up its evaluation and avoid the need to loop over array elements.
The warning is just a comment about the internal functioning of Matlab. You can eliminate it by replacing
^ with .^ or by using a symbolic function instaed.
More Complicated Calculations - IMPORTANT!
It's important to realize that if f is a function handle and x is symbolic then f(x) and consequently things
like diff(f(x)) are symbolic too. This means we need to use subs in places. For example if we wish
to find a second derivative of a function handle and then plug in:
clear all;
f = @(x) 1/x^3+log(x-2);
4
Chapter 13 - Function Handles
syms x;
subs(diff(f(x),2),3)
ans =
-77/81
Take a moment to understand what this does, keeping in mind the fact that x is nested inside f(x) which
is inside diff which is inside subs.
Similarly suppose we wanted to start with a function handle, differentiate, divide by x and then plug in:
clear all;
f = @(x) x^3+2/x;
syms x;
subs(diff(f(x))/x,5)
ans =
1873/125
Published with MATLAB® R2014a
5
Chapter 14 - Publishing
Table of Contents
What is publishing? .............................................................................................................
Example ............................................................................................................................
Basic Structure ...................................................................................................................
Blank Lines ........................................................................................................................
1
1
3
3
What is publishing?
MATLAB's publish feature is a powerful tool that allows you to create nicely formatted documents
from your m-files. We used publish to create all the pdfs for this tutorial. More commonly publish
is used to produce html files.
Publish allows you to easily format text and also to execute "live" MATLAB commands, inserting the
results directly into your documents. The output from the publish command can be formatted as html,
pdf, Word documents, Power Point documents, and LaTex. The default setting is to produce html files.
Example
We don't want to overwhelm you with too many details, so we will just show you the basics using one
simple example.
Begin by editing an M-file file called publishexample.m. Just type
edit publishexample.m
at the command prompt in Matlab.
Now enter the following into your m-file (we highly suggest cutting and pasting.) If you're using the Matlab
editor then it may highlight the code in different colors.
%% First Thing
% The previous line begins with %% followed by some text. When
% published this will show up as a distinct section with its
% own label in the html document. Now here is a calculation.
% To do the calculation we stop using % in front. The blank
% lines are not mandatory but they do make things much easier
% to read:
2+2
%%
% The previous line just has %% but no text. It's still critical to
% have it there because we're beginning a new section of text. It will
% NOT have a label though. You can't just go from Matlab code
% straight back to %, you need to have %% first. Now here's some
% other stuff:
1
Chapter 14 - Publishing
syms x;
ezplot('x^2')
%% A New Section Label
% Back to text with another %% but now a section label again because
% it's %% followed by the label.
%
% Notice that we can have % by itself which just begins a new
% paragraph within the text section.
%
% Here are some _italics_ and here is some *boldface*. Here is some
% |fixed-width font| which looks like code.
%
% Here's another calculation:
solve('2*x+3')
%%
% Now back to text. We can do some numbering but before the numbering
% we must have a line with a simple %.
%
% # One
% # Two
% # Three
%
% A simple % line ends the counting. Here is another calcuation:
diff('sin(x^2)')
%%
% Now if we go back to text and try more numbers they restart at
%
% # One
% # Two
%
% Here are some bullets, again preceeded by %:
%
% * Bam!
% * Kapow!
%
%% Lastly, here's a plot. Plots show up nicely
% inline with the text.
ezplot(x*sin(x))
%% The end.
% Done!
Now... try publishing this m-file by pressing the "publish" button in the editor which looks like little
document speeding across the page.
Did you try it? When you click "publish", a nicely formatted webpage should appear appear on your screen
in your default web browser. The resulting html file is also automatically saved on your computer in a
directory called "html", which is created inside the current working directory. The output is impressive!
Really compare it to the m-file which you published and think about how it worked.
2
Chapter 14 - Publishing
Basic Structure
The basic structure is pretty easy. The publishable m-file is broken up into blocks of text and blocks of
Matlab code which are actually executed.
Blocks of text look like either:
%% Section heading.
% Blah Blah
% Blah
or:
%%
% No section heading there.
% Blah
If there's a section heading then it publishes in boldface and gets a link at the top of the webpage.
Within each text block you can make the text pretty by:
• Surrounding text with _ for italics.
• Surrounding text with * for boldface.
• Surrounding text with | for fixed-width font.
You can construct numbered lists by first starting with a line containing just % and then each succesive
numbered item has a % # in front. End the list with another % line.
Likewise you can construct bulleted lists by first starting with a line containing just % and then each
succesive numbered item has a % * in front. End the list with another % line.
You can do more with publishing but those are the basics.
Blank Lines
It is important to notice where I've put blank lines in the M-file for publishing. Specifically there are blank
lines between code and comments. You must have these blank lines!
Published with MATLAB® R2014a
3
Chapter 15 - Basic Programming
Table of Contents
Introduction ........................................................................................................................ 1
Displaying Stuff - disp ...................................................................................................... 1
Condition - if ................................................................................................................... 1
Loop - for ........................................................................................................................ 2
More Examples of Loop - for ............................................................................................. 5
Using for Loops to Store Answer in Vectors ......................................................................... 6
Loop - while .................................................................................................................... 7
The General Idea when Comparing Successive Values ............................................................. 10
Closing ............................................................................................................................ 11
Introduction
If you've had any programming experience at all then most of this lesson will be straightforward. Here
we'll introduce some basic programming structures which will show up in our M-files.
Displaying Stuff - disp
We know that if we do a calculation the output is printed unless we suppress this by ending the calculation
with a semicolon. However what if we wish to display something like some text or the variable without
the x = which Matlab automatically inserts? Well there are many ways to do this but the disp command
(display) is the easiest. The format is disp(X) where X is either a string or a vector of strings. Keep in
mind though that numbers can be converted to strings with num2str and symbolic expressions to strings
with char. Here are some examples. Make sure you parse them carefully to understand what they do!
disp('Hello World!')
Hello World!
x=2;
disp(['The value of x is ',num2str(x)])
The value of x is 2
syms t;
disp(['The derivative of t^2 is ',char(diff(t^2,'t'))])
The derivative of t^2 is 2*t
Condition - if
An if statement can be used to execute a statement if a certain condition is met. The general simplest
syntax is:
if expression
statement
end
1
Chapter 15 - Basic Programming
We should pause to note here that Matlab is situation-aware. By that we mean that if you type the line
if (x>3)
into Matlab and press Enter nothing will happen. Matlab is waiting for you to finish your if-statement-end
structure. Matlab will do nothing until you type end and press Enter. So type the following exactly as
you see it:
x=5;
if (x>3)
disp(['x was bigger than 3 so here is twice it: ',num2str(2*x)])
end
x was bigger than 3 so here is twice it: 10
Here we see that since x is in fact greater than 3 the code between if and end is executed. On the other
hand the following gives no output.
x=2;
if (x>3)
disp(['This disp will not execute, how sad!'])
end
Here since the condition is false the code is not executed. If we want to test multiple conditions and if we
wish to have a catch-all which occurs if none of the conditions are met we can do that with the general
form as follows:
if expression1
statement1
elseif expression2
statement2
...
else
catchallstatement
end
What happens here is that first expression1 is tested and if it's true then statement1 is executed.
If not then expression2 is tested and if it's true then statement2 is executed and so on. If none
of them are true then catchallstatement is executed. As in the previous example Matlab will do
nothing until you end.
IMPORTANT: If you need the if statement to be a compound statement you can use & for and and |
for or. For example
if (x>0 & x<10)
will check both conditions whereas
if (x<3 | x>5)
will require only one to be true.
Loop - for
Supose we wanted to assign the variable x to each of the numbers 1 through 5 and then print 2 times each.
We could do this:
2
Chapter 15 - Basic Programming
x=1;
disp(num2str(2*x))
x=2;
disp(num2str(2*x))
x=3;
disp(num2str(2*x))
x=4;
disp(num2str(2*x))
x=5;
disp(num2str(2*x))
2
4
6
8
10
This is pretty tedious. If we needed to do something complicated with each of the x values it would be
even worse and if we needed to assign x to each of the numbers 1 through 100 even worse still. The for
loop allows us to do this in a much more straightfoward manner. Abstractly it works like this:
for x=(tell it which x values to do)
what to do with each x
end
The way we tell Matlab to go through all the x values is with a vector. So now the commands above with
the variable x can be taken care of with either
for x=[1 2 3 4 5]
disp(num2str(2*x))
end
2
4
6
8
10
or
for x=[1:5]
disp(num2str(2*x))
end
2
4
6
8
10
Like with if nothing will happen until you end so go ahead and type this straight into Matlab as above.
Here is another example with vector notation:
for x=[0:pi/6:pi/2]
disp(['The sine of ',num2str(x),' is ',num2str(sin(x))])
end
3
Chapter 15 - Basic Programming
The
The
The
The
sine
sine
sine
sine
of
of
of
of
0 is 0
0.5236 is 0.5
1.0472 is 0.86603
1.5708 is 1
The variable x runs from 0 to pi/2 in steps of pi/6 and sin(x) is taken at each step.
The general form is:
for v=vector
statement1
statement2
...
end
Here v is the vector which says which values x will run through and statement1, statement2,...
are statements which will be executed.
Consider the following example which finds the derivative of x^2 through x^7.
syms x;
for n=[2:7]
diff(x^n,x)
end
ans =
2*x
ans =
3*x^2
ans =
4*x^3
ans =
5*x^4
ans =
6*x^5
ans =
7*x^6
4
Chapter 15 - Basic Programming
Now then, for loops don't actually have to do anything with the looping variable, it can just be used as
a counter. For example the following just says Hi! four times.
for n=[1:4]
disp('Hi!')
end
Hi!
Hi!
Hi!
Hi!
Here is a for loop which does something more - it adjusts a value as it goes along. Imagine you wanted
to start with the number 1.2 and square it five times. You can do this as follows. Notice how the code
works. mynum is initially set to be 1.2 and is then adjusted within the for loop each time. Within the
loop mynum is reassigned.
mynum=1.2;
for n=[1:5]
mynum=mynum^2;
disp(mynum)
end
1.4400
2.0736
4.2998
18.4884
341.8219
If you just wish to print the final answer you can do:
mynum=1.2;
for n=[1:5]
mynum=mynum^2;
end
disp(mynum)
341.8219
More Examples of Loop - for
Here are some other examples:
Example 1: Adding the numbers 1 through 10.
How can we add the numbers 1 through 10 in Matlab? We first assign a total with the value 0 and then
we successively add the numbers 1 through 10 to that total:
total=0;
5
Chapter 15 - Basic Programming
for n=[1:10]
total=total+n;
end
disp(total);
55
Example 2: The function f(x)=2.5x(1-x) appears in certain population dynamics. The way it works
is that if you plug in one year's population it outputs the next year's population. Here's a matlab loop which
gives the next five years' populations if the initial population is 0.3 (think thousands):
f = @(x) 2.5.*x.*(1-x);
pop = 0.3;
disp(['Start at ',num2str(pop)]);
for n=[1:5]
pop=f(pop);
disp(['Next at ',num2str(pop)]);
end
Start at 0.3
Next at 0.525
Next at 0.62344
Next at 0.58691
Next at 0.60612
Next at 0.59685
Using for Loops to Store Answer in Vectors
Often we may do a calculation which requires us to store several different values. We can do this by storing
those values in a vector. Mathematically a vector is just an ordered collection of numbers. We assign
vectors using [] notation. Here is an example:
a = [1 -2 4 5]
a =
1
-2
4
5
Here a is a vector containing four numbers. If we want to access just one of those four we use () notation:
a(2)
ans =
-2
Or to change one of them we can assign this way. Notice that Matlab gives us the entire new vector back
to see.
a(3)=17
6
Chapter 15 - Basic Programming
a =
1
-2
17
5
Suppose now we want to do a calcuation of something like sin(2^1), sin(2^2), ..., sin(2^7) and
store them all in a vector. First we assign a vector with 7 entries and then we use a for loop to do the work:
v=[0 0 0 0 0 0 0];
for i=[1:7]
v(i)=sin(2^i);
end
Then we can see it. Notice that because the vector stretched beyond the screen width matlab labeled the
entries (columns) on each line.
v
v =
0.9093
-0.7568
0.9894
-0.2879
0.5514
0.9200
Or just one entry
v(2)
ans =
-0.7568
Loop - while
The trouble with a for loop is that it executes a statement a certain fixed number of times. Often in
mathematics we wish to execute a statement an unknown number of times until a criteria is met. For
example when we do the bisection method to find a root we iterate until we're close enough, which could
mean until our interval is some certain size. If we do a Riemann sum we might wish to increase the number
of subintervals until our sum settles down, meaning it doesn't change by more than say 0.1 from iteration
to iteration. In Matlab this is done most easily with a while loop. The general form of this loop is:
while (some conditions are met)
statement1
statement2
...
end
What happens in this case is that Matlab enters the while statement and tests the conditions. If they're true it
proceeds through the statements. At the end it goes back to the beginning and tests again. If the statements
(any of them) are ever false it ends the loop. Here is a simple example with its output:
x=3;
7
0.7210
Chapter 15 - Basic Programming
while (x<10)
disp(['The value of x is ',num2str(x)]);
x=x+1;
end
disp(['At the final exit the value of x is ',num2str(x)]);
The value of
The value of
The value of
The value of
The value of
The value of
The value of
At the final
x is
x is
x is
x is
x is
x is
x is
exit
3
4
5
6
7
8
9
the value of x is 10
What this code does is starts by assigning the value x=3. The while statement checks the value, finds
it's less than 10 and goes into the loop. It prints the text and value and then increments the value by 1 (this
is what the x=x+1 does). Then it goes back and tests x<10 again. The final time the statements in the
loop will be executed is when x=9. At the end of this iteration Matlab does x=x+1 at which point x=10
and then Matlab goes back to the while, sees it fails and drops out. Keep in mind that x=10 upon exit
but the code does not execute with x=10.
This next example is related to one of the earlier for loops. Again we start with the number 1.2 but
now we repeatedly square the number until we get above 1000000 and then we stop. This happens pretty
quickly! Notice what the while does - it checks if mynum is <=1000000 and if so, it keeps going,
squaring over and over. We've made it neater using disp.
mynum=1.2;
while (mynum <= 1000000)
disp(['Now the number is ',num2str(mynum)])
mynum=mynum^2;
end
disp(['Dropping out of the loop the number is ',num2str(mynum)])
Now the number is 1.2
Now the number is 1.44
Now the number is 2.0736
Now the number is 4.2998
Now the number is 18.4884
Now the number is 341.8219
Now the number is 116842.2058
Dropping out of the loop the number is 13652101047.4993
Here is a while loop which divides a number by 2 over and over until the result is less than or equal
to 1. Think " while the number is greater than 1, keep dividing." Furthermore this code only prints the
final result.
mynum=2753;
while (mynum > 1)
mynum=mynum/2;
end
disp(mynum)
0.6721
8
Chapter 15 - Basic Programming
Here's a more sophisticated example. It calculates successive partial sums 1/1+1/2+...+1/n starting
with n=1 until successive sums are within 0.01 of each other. All the while it prints out a summary. Note
the use of a new variable within the loop so that the old variable is not immediately lost. Also note that
oldvalue is initially set to be large enough to get us into the loop.
oldvalue = 1/1;
newvalue = 1/1+1/2;
n = 2;
while (abs(newvalue-oldvalue) >= 0.1)
disp(['Adding up to 1/',num2str(n),' yields ',num2str(newvalue)]);
oldvalue = newvalue;
n = n+1;
newvalue = newvalue+1/n;
end
Adding
Adding
Adding
Adding
Adding
Adding
Adding
Adding
Adding
up
up
up
up
up
up
up
up
up
to
to
to
to
to
to
to
to
to
1/2 yields 1.5
1/3 yields 1.8333
1/4 yields 2.0833
1/5 yields 2.2833
1/6 yields 2.45
1/7 yields 2.5929
1/8 yields 2.7179
1/9 yields 2.829
1/10 yields 2.929
Here's the same with 1/0!+1/1!+1/2!+...+1/n! instead, the tolerance set to
0.000000000000001 and format long for more decimals. We've had to use num2str(sum,20)
too which forces num2str to display up to 20 decimal digits rather than the usual four. If you remember
something about series it may be familiar to you!
Hint: What does 1/0!+1/1!+1/2!+... converge to?
format long;
tol = 0.0000000000000001;
oldvalue = 1/factorial(0);
newvalue = 1/factorial(0)+1/factorial(1);
n = 1;
while (abs(newvalue-oldvalue) >= tol)
disp(['Adding up to 1/',num2str(n),'! yields ',num2str(newvalue,20)]);
oldvalue = newvalue;
n = n+1;
newvalue = newvalue+1/factorial(n);
end
Adding
Adding
Adding
Adding
Adding
Adding
Adding
Adding
Adding
Adding
Adding
up
up
up
up
up
up
up
up
up
up
up
to
to
to
to
to
to
to
to
to
to
to
1/1! yields 2
1/2! yields 2.5
1/3! yields 2.6666666666666665186
1/4! yields 2.7083333333333330373
1/5! yields 2.716666666666666341
1/6! yields 2.718055555555555447
1/7! yields 2.7182539682539683668
1/8! yields 2.7182787698412700372
1/9! yields 2.7182815255731922477
1/10! yields 2.7182818011463845131
1/11! yields 2.7182818261984929009
9
Chapter 15 - Basic Programming
Adding
Adding
Adding
Adding
Adding
Adding
up
up
up
up
up
up
to
to
to
to
to
to
1/12!
1/13!
1/14!
1/15!
1/16!
1/17!
yields
yields
yields
yields
yields
yields
2.7182818282861687109
2.7182818284467593628
2.7182818284582301871
2.7182818284589949087
2.7182818284590428703
2.7182818284590455349
The General Idea when Comparing Successive
Values
It's extremely common to continue a calculation until some particular tolerance is reached. To help you
see what the code should look like here's a code template. The idea for this template is that we're finding
successive values of a variable for n=1, n=2, ... until they differ by less than tol.
Set oldvalue = the first value, corresponding to n=1.
Set newvalue = the second value, corresponding to n=2.
Set n = 2.
while (abs(oldvalue-newvalue)>=tol)
oldvalue = newvalue;
n=n+1;
newvalue = find the new value for this new n.
end;
At this point, newvalue has the final calculated value.
Please make sure you see how this works. First we find the first two values, oldvalue and newvalue
we're interested in. We set n=2 because that's how far we've gone. We then start the loop, comparing
these values (note we compare while the difference is too big!) Inside the loop we make oldvalue
equal to newvalue, add 1 to n and then find a new newvalue. The while loop check then happens
again and we continue.
In general the only things that need to be done to turn this into workable code is:
1. Set the oldvalue correctly for whatever you're finding.
2. Set the newvalue correctly for whatever you're finding.
3. Inside the loop, set the newvalue correctly for an unknown n.
Make sure to look at the two examples given earlier and see how they fit this template. The only additional
thing they have is the disp statement.
Just to finish it off, here's one more example. It finds values of the integral from 1/x^2 from 1/n to 2
as n gets larger and larger, starting at n=1 until successive values differ by less than 0.001. The disp
at the end just displays it.
syms x;
tol = 0.001;
oldvalue = int(x^2,1/1,2);
newvalue = int(x^2,1/2,2);
n=2;
while (abs(oldvalue-newvalue) >= tol)
oldvalue = newvalue;
n = n+1;
newvalue = int(x^2,1/n,2);
10
Chapter 15 - Basic Programming
end;
disp(double(newvalue));
2.665694849368319
Closing
In closing we should mention that Matlab is a full-fledged programming language and there are many
commands other than these. We recommend searching the Web and the help files to see what else can be
done. We will explore other commands as we venture into M-files.
Published with MATLAB® R2014a
11
Chapter 16 - Function M-Files Part 1
Table of Contents
What is a Function M-File? ..................................................................................................
A Simple Function M-File ....................................................................................................
The General Idea ................................................................................................................
A (More) Complicated Function M-File ..................................................................................
1
1
2
3
What is a Function M-File?
Suppose you wished to write your own function which you could access every time you loaded up Matlab.
Suppose it couldn't be as simple as we've seen before - perhaps it needs to test the values passed to it like
a piecewise function in calculus. Suppose the function is a process that needs to calculate and return a
value. How can we do this?
Matlab allows all of this very conveniently using function M-files. At its most basic level an M-file is a text
file containing a series of Matlab commands. Typically these files have the extension .m which is where
they get their name. The location of these files is important also since otherwise Matlab won't know where
to find them. The best and perhaps most obvious place to put them is in the current working directory.
This is the directory indicted in the leftmost directory window "Current Directory" on Matlab. If you wish
to store your M-files in another directory you'll have to add that directory to the path. You can do this by
hunting under the "File" pull-down menu.
A Simple Function M-File
Let's start by creating a function M-file which you'll then have in your directory for future use. We'll make
it something useful from calculus. We know that an object dropped from a height of h meters will strike
the ground in sqrt(h/4.9) seconds. Let's create a function M-file named HowLong. To do this type:
edit HowLong.m
Matlab will verify that you'd like to open a new file (in the current working directory) so click "Yes".
In the editor window which opens type the following code:
function t=HowLong(h)
t=sqrt(h/4.9);
end
Note: The end at the end of the m-file is not critical but it is good programming practice and I will always
do it. I recommend you do too. This way the function has an end and each for, while and if has an end.
Save the M-file. From now on we can access our function simply by calling the HowLong function. You
can do this anytime you ever run Matlab (now or in the future) because the file (and hence the function)
will be there until you delete it.
HowLong(100)
Stop to anaylze for a minute how this function works. The keyword function tells Matlab that we're
writing a function. The t= indicates the variable which we'll use to return the result. The name HowLong
1
Chapter 16 - Function M-Files Part 1
is the name of the function and the parenthetical h indicates that a single value will be passed to the function
and in that function the value will be called h.
We can also do things like:
syms x;
HowLong(x)
or:
syms q;
HowLong(q)
The General Idea
The general outline of a function M-file is as follows:
function r=functionname(a,b,...)
do stuff
any matlab stuff
by the end assign
r = whatever you want to return
end
You can do any Matlab commands you like in the middle provided that you assign your return value r
before you end the function.
Note that the use of r is arbitrary, you can use any variable you wish, but it must be the variable
you assign to return!
The functionname must correspond to the filename functionname.m you use. Here are some other
simple function m-files and what they do:
Example 1: This will accept one value a and return that value plus 3.
function bah = justin1(a)
bah = a+3;
end
Example 2: This will accept two values a and b, solves a*x+b, printing the result since the line does not
end with a semicolon ;, and then assigns (and therefore returns) s=a-b.
function happy = justin2(a,b)
syms x;
solve(a*x+b);
happy = a-b;
end
Example 3: This does ezplot on a*x^2 and returns a-8. It completely ignores b. In practice you'd never
ignore a parameter (otherwise what would be the point of having it?) but this just shows that it will work.
function y = justin3(a,b)
syms x;
ezplot(a*x^2);
y = a-8;
end
2
Chapter 16 - Function M-Files Part 1
A (More) Complicated Function M-File
Function M-files do not need to be so simple. We can define a piecewise function. Try this new M-file:
edit pwisef.m
In the function place the following:
function y=pwisef(x)
if (x <= 0)
y = -x;
else
y = sin(x);
end
end
Note: The first end ends the if/else and the second end ends the function. The result is as expected:
pwisef(-1)
versus
pwisef(pi/4)
But if you try the following you'll get an error:
pwisef(x)
Why is this? The answer is fairly straightforward. The pwisef takes the value x as a parameter and then
hits a brick wall when it tries to execute if (x<=0). How can it compare x to 0 if it doesn't know
x? It can't.
Published with MATLAB® R2014a
3
Chapter 17 - Function M-Files Part 2
Table of Contents
Multiple Parameters .............................................................................................................
Passing Functions to Functions ..............................................................................................
A More Complicated Example ..............................................................................................
Documenting Your M-File ....................................................................................................
1
1
2
3
Multiple Parameters
Function M-files can take more than a single variable as an argument. For example suppose we wish to
write a function which calculates the area of a rectangle with length l and width w. We can do this with
the following code placed in a function M-file called rectarea.m:
function a=rectarea(l,w)
a=l*w;
end
Easy! Then we call the function as expected:
rectarea(15,72)
ans =
1080
Passing Functions to Functions
The last thing we want to look at is how to pass a function to a function M-file as one of its arguments. For
example suppose you wished to write a function M-file which took two arguments, one being a function
and the other a constant, and then it plugged the constant into the function and returned the result. Nothing
sophisticated!
We do this in a fairly obvious way. The thing to keep in mind is that Matlab can accept functions as
parameters in various ways. Here are a couple. First create the M-file plugin:
function r=plugin(f,x)
r=f(x);
end
This is it. Now we can pass any function as the first argument f provided that f(x) makes sense. For
example:
f = @(x) x^2-3;
plugin(f,-1)
1
Chapter 17 - Function M-Files Part 2
ans =
-2
or without a declaration of the function first:
plugin(@(x) x^2-3,-1)
ans =
-2
A More Complicated Example
Here's a function M-file which takes a function handle, a value and a tolerance. It approximates the derivative of the function at that value by using closer and closer approximations by tangent lines until successive approximations differ by less than the tolerance.
function r = derivativeapprox(f,a,tol)
h = 1;
oldapprox = (f(a+h)-f(a))/h;
h = h/2;
approx = (f(a+h)-f(a))/h;
while (abs(approx-oldapprox)>=tol)
oldapprox = approx;
h=h/2;
approx = (f(a+h)-f(a))/h;
end
r = approx;
end
Here is some sample output:
derivativeapprox(@(x) x^3,2,0.01)
ans =
12.005860328674316
Take some time to see how this function works since you'll need to write similar examples yourself. We're
approximating the derivative by looing at (f(a+h)-f(a))/h as h gets closer to zero (remember that
definition of the derivative?) So we start with h=1. We find an initial approximation called approx
using that h. Since we're going to be comparing successive approximations we need to preseve the old
approximation each time so we create a variable oldapprox. At the start there's no old approximation so
we give it a value which guarantees that we'll get into the while loop successfully the very first time. The
while loop first saves the approximation as the old approximation, changes the value of h by cutting it
in half, then finds the new approximation. Thus after each iteration of the while loop we have the (new)
approximation and the old approximation to compare. Note that the abs is critical. Do you know why?
2
Chapter 17 - Function M-Files Part 2
Documenting Your M-File
To close this section we'll put in a vote for a good programming practice - documentation! At the Matlab
prompt we can always type help name to get information on command like help ezplot. Now that
we've learned to write function M-files we should put some documentation in those files so that we can
get help on them. Modify your rectarea.m file to read:
function a=rectarea(l,w)<br>
% This function rectarea(l,w) finds the area of a rectangle with
% length l and width w.
a=l*w
end
Then try:
help rectarea
This function rectarea(l,w) finds the area of a rectangle with
length l and width w.
The text which is after the % symbols in the M-file will be printed out as a response to help rectarea
being called.
Published with MATLAB® R2014a
3
© Copyright 2026 Paperzz