Part 1: Elementary Calculations: MATLAB Tutor
Part 1: Elementary Calculations: MATLAB Tutor
To send each command entry instruction to MATLAB for processing, press the
RETURN or ENTER key on your keyboard.
2 + 3
2 - 3
3. Enter
2*3
4. Enter
6/3
5. Enter
2^3
Now you know how to add, subtract, multiply, divide, and raise a number to a
power in MATLAB – much the same way you do with a calculator or with other
software packages.
The most recent result is always stored in a variable called ans (for ‘answer’).
Only the very latest result is stored there.
6. Enter
ans
2*ans
You can compute with the result stored in ans in the same way that you
can with any number.
8. Press the up arrow once, and then press Enter.
9. Press the up arrow several times, and note what happens. You can
recover all your previous commands and re-execute them if you desire.
10. Enter
sqrt(5)
11. Enter
pi
12. Enter
i
You can use the right and left arrows on the keyboard to move right and left to
edit a command line. Thus, you can correct mistakes by recalling a command
with the up arrow and editing to correct it. You can type over a symbol you want
to change or use the backspace key to delete it.
13. Use the up arrow to recover the command sqrt(5). Edit it using the right
and left arrows and compute sqrt(8+pi).
14. Enter
format long
pi
15. Enter
format short
pi
16. Enter
format short e
format rational
format hex
format short
MATLAB Tutor
Part 2: Comments
1. Enter
In Part 4 of this tutorial, you will learn how you can save the work you do during a
MATLAB session into a "diary" file. You should include many MATLAB
comments in your work so that later, when you read your diary file, you can see
what you were doing.
MATLAB Tutor
Part 3: Variables
1. Enter
x=3
2. Enter
y=2
3. Enter
2*x+y
Note that the variable x has been assigned the value 3, and the variable y has
been assigned the value 2, so the algebraic expression you typed was evaluated
using those values, and the result has been stored in the variable ans.
4. Enter
x
5. Enter
y
6. Enter
z=5;
7. Enter
z
Note the effect of the semicolon; use it when you do not want to see your input
echoed. The computer still knows what is stored in the variable z.
8. Enter
2+x-y*z
9. Enter
ans
10. Enter
ans + 3
11. Enter
2*ans
12. To see what variable names you have used in your current session, enter
who
13. Enter
a = 3;
b = 5;
c = 1;
discr = b^2 - 4*a*c;
14. Enter
discr
15. Enter
DISCR
Is MATLAB case-sensitive?
There may in fact be times when you want to use the letter a to represent a real
number and the letter A to represent a matrix, and MATLAB will let you do that.
Remember, if you ever forget what variables are in current use, use the who
command. (Or, for more information, use the whos command!)
16. Enter
sqrt(discr)
17. Enter
You will make use of vector variables on many ocassions in MATLAB. A vector
is just a list of numbers. To enter a vector, enclose its components in square
brackets and separate them by commas or blanks. This gives you a "row vector."
which displays horizontally. You can make it into a "column vector" by putting a
single quote mark after it.
18. Enter
20. Enter
2*x
21. Enter
x/3
22. Enter
3.^x
25. Enter
x/(2+x)
26. Enter
Make sure you understand what is going on before continuing to the next part of
the tutorial.
MATLAB Tutor
If you want to save the work you do in a MATLAB session, you must create a
diary file. This file will contain a complete transcript of everything you type into
the computer, and everything the computer responds. Later, you can edit it with
any word processor.
To start a diary file called ‘Lab1.txt’ on the diskette in drive a, for instance, you
would type
diary a:Lab1.txt
and press Enter. You probably won’t see anything happen, but the computer is
keeping track of your work.
diary off
Typing diary on will go back to saving your work at the bottom of your previous
diary file. If diary is on when you quit MATLAB, your diary file will be
automatically closed.
When you quit your MATLAB session, the values of all your variables are lost.
Your diary file only keeps a log of what has appeared on your screen, not stored
values of variables. If you want, before you quit MATLAB, you can save the
current values of variables into a file to use in a future session. The following
command would save the values into a file called myfile:
save myfile
The values of all the variables in your workspace will be saved in binary form,
unreadable by humans, into a file called myfile.mat in your working directory. In a
future MATLAB session, to load all these variable values into the new session,
use the command:
load myfile
MATLAB Tutor
All of the standard mathematical functions, plus many other functions, are
available in MATLAB. Functions operate both on both single numbers and on
vectors. You can use MATLAB just like a calculator.
1. Enter
4. Enter
x = -1: 0.1: 2
y = exp(x)
plot(x, y)
Usually, we don’t want to print out the x and y lists so we use a semi-colon to
suppress the output.
We can control the graph's color and line style by adding an extra parameter to
the plot command. Choices for colors are 'c' (cyan), 'm' (magenta), 'y' (yellow), 'r'
(red), 'g' (green), 'b' (blue), 'w' (white), and 'k' (black). Line style choices are '-' for
solid (the default), '- -' for dashed, ':' for dotted, and '- .' for dash-dot. Let's make
the graph red and dotted.
5. Enter
x = - 4: 0.5: 3;
y = cos(x);
plot(x, y, 'r:')
MATLAB has marker types '+', 'o', ' * ', and 'x' and the filled marker types 's' for
square, 'd' for diamond, '^' for up triangle, 'v' for down triangle, '<' for right
triangle, '>' for left triangle, 'p' for pentagram, and 'h' for hexagram. If you specify
a marker but not a line style, your graph only has disconnected markers. Here we
plot blue diamonds.
6. Enter
plot(x, y, 'bd')
Using unconnected markers is just what we want in order to produce a scatter-
plot of data points. Rarely do we want such points connected by lines.
7. Enter
x = [1, 2, 4, 5, 7]
y = [10, - 4, 3, 1, 6]
plot(x, y, 'ro')
We can plot more than one graph on a single plot by using the hold on
command to save the old plot and then make another plot the usual way. Below,
we add the line y = - 3*x + 15 to the last scatter-plot.
8. Enter
hold on
x = 1: 0.2: 7;
y = - 3*x + 15;
plot(x, y, 'b')
There are additional commands that allow us to control the "window" of the
graph, add grid lines, put labels on the axes, add a title for the graph, and specify
a legend. We will add these features to our plot.
9. Enter
There is another, sometimes easier, way to make a plot in MATLAB; using the
fplot function. You simply put the name of your function in single quotes. You
can use line markers for the curve like '- +', '- x', '- o', and '- *'. You have no
choice of color and generally have less control over the appearance of the plot.
To find out more about features of fplot, type "help fplot" at the MATLAB prompt.
10. Enter
clf % clears figure window
fplot('sin(x)', [- 3, 3])
grid on
Experiment with combinations of the commands used for plotting to be sure you
feel comfortable using them.
MATLAB Tutor
1. Use a text editor to create a file that contains the following lines. Save the
file in your working directory under the name tester.m.
d2r = pi/180
a = sin(30*d2r)
b = (1 + a)/4
tester
There will be occasions when you will need to define your own specialized
functions which are not built into MATLAB. You do this by using a special kind of
"function" m-file. As with standard functions like sin(x), a function m-file accepts
input arguments and returns outputs.
An example function m-file is given below. It accepts the input argument x and
returns y = fun(x). Note that the first line contains the key word "function" and
describes inputs and outputs. The output value must be assigned within the
"program" to the variable y which appears before the equals sign on the first line
of the file. The m-file must be given the same name as the function, namely
fun.m.
3. Use a text editor to create a file that contains the following lines. Save in
your working directory under name fun.m.
function y = fun(x)
d2r = pi/180 ;
y = 3*cos(x*d2r) - 1 ;
fun(45)
5. Enter
z = 30
a = fun(z)+ 8
User-defined functions can be plotted as easily as built-in ones. We will use the
plot commands we learned in Part 5 of this Tutorial.
6. Enter
You can define functions that take inputs of more than one variable. Output can
likewise be more than one variable. Both input and output variables can be
vectors.
MATLAB Tutor
If you are using the Student Version of MATLAB, then you have access to the
optional Symbolic Math Toolbox. If you are using a professional (non-student)
version, then you must purchase this toolbox separately. If you do not know
whether your version of MATLAB is equipped with the toolbox or not, try a few of
the following exercises. If they work, you’ve got it. If not, you will have to skip
over any exercise that asks you to perform computations with variables that have
not been assigned numeric values and should be treated as symbols.
syms x
f = 3*x^2 - 5*x + 1
ezplot(f, [- 3,2])
4. To substitute a number or a symbol into a symbolic expression, use the
subs command. Enter
subs(f, x, - 2)
syms q
subs(f, x, q)
5. Below we declare four symbolic variables at once using the syms
command and solve a quadratic equation using the solve command.
Enter
MATLAB Tutor
Part 8: Differentiation
MATLAB can find the derivative of symbolic expressions. Higher derivatives can
also be found easily. These derivatives can be evaluated for arbitary values of
the independent variable.
syms x
g = x^2*cos(x)
2. Now enter:
diff(g, x)
Then enter:
diff(g, x, 2)
3. If you want to calculate the derivative of an expression that you have not
yet entered, just replace g by the expression. For example, enter:
diff(x^3-x^2+2, x)
syms a
diff(x^3 - a*x^2 + 2, x)
diff(x^3 - a*x^2 + 2, a)
What is the role of the symbol after the comma in the differentiation
expression?
4. Now, suppose you want to evaluate the derivative dg/dx at x = 2.1. Enter:
gp=diff(g, x)
Then enter:
subs(gp, x, 2.1)
Part 9: Integration
MATLAB can find both an indefinite integral (i.e., antiderivative) and a definite
integral of a symbolic expression. That assumes an elementary antiderivative
exists. If not, MATLAB can compute a very accurate numerical approximation to
the definite integral.
syms x
Then enter
int(x*sin(x), x)
diff(ans, x)
syms a
Then enter
int(a*sin(x), x)
Now enter
int(a*sin(x), a)
int(sin(x^2), x)
int(x*sin(x), x, 0, pi/2)
5. Now try this method on the integral of sin ( x5 + x3 ) over the interval
[0,pi/2].
6. If you know that all you want is a numerical estimate, you can use
MATLAB's numerical integrator called quad8. No symbolics are involved.
Enter:
quad8('fun', 0, pi/2 )
The significance of using the quad8 function is that MATLAB does not try
to find a symbolic solution before starting on the numerical estimate.
7. Use MATLAB to find the exact value of each of the following integrals.
(Type inf for the infinity symbol.)
o The integral of 1/(1+x2) from 0 to 1,
o The integral of 1/(1+x2) from 0 to Infinity,
o The integral of 1/(1+x4) from 0 to Infinity.
MATLAB Tutor
MATLAB has an extensive collection of help messages. If you know the name of
a command, you can find the proper syntax for the command and examples of its
use by typing help command_name. That's assuming you know the command's
name.
1. The commands are stored in various MATLAB libraries. Let's get a list.
Enter:
help
2. Suppose you want to see if MATLAB has the elementary function
arctangent, the inverse tangent function. Look down the list of libraries.
There seems to be a likely candidate there. You can identify the directory
by using only the last part of the filename. Enter:
help elfun
3. Sure enough, the list has a function called atan on it. Enter:
help atan
Practice finding other MATLAB commands and getting help on their use.
MATLAB Tutor
MATLAB m-files designed for use in conjunction with the Connected Curriculum
Project modules are available for downloading to your computer.
When you click on the MATLAB icon that appears on the table-of-contents page
of a module, you will get instructions about how to download a "package" of m-
files that are coordinated with the module. For example, for the module named
Numerical Solutions of Differential Equations, there are seven m-files in the
package, namely, numdiff1.m through numdiff5.m, dfun.m, and slpfield.m.
1. Click on the MATLAB icon below and you will see the page of instructions for
downloading and uncompressing the package of m-files for the Numerical
Solutions of Differential Equations module. Go ahead and download the
appropriate package file.
After you have downloaded and uncompressed the package of m-files, then to
use the instructions in the file numdiff1.m, for example, all you have to do is type:
numdiff1 at the MATLAB prompt and press Enter. The instructions will appear in
your MATLAB window. That assumes, of course, that MATLAB knows which file
on your computer system contains numdiff1.m.
There are two ways that you can tell MATLAB where to find the numdiff1.m file.
You can either (1) make sure the file is in your working directory, or (2) add the
name of the file that contains numdiff1.m to MATLAB’s search path.
You can make sure you are in the directory containing the m-files you need
before you even start-up your MATLAB session. You can also change your
working directory while you are in MATLAB as we now demonstrate.
2. If you are in MATLAB, to find out what your working directory is, enter:
pwd
dir
You can navigate through your directories to find the one containing numdiff1.m
by using the "cd" command (which stands for "change directory").
5. Pick the subdirectory you want to go to in the subdirectory list inside the
directory. To go there, enter:
cd sub_name %change "sub_name"
An alternative way to tell MATLAB where to find your m-files, especially if they
are in two different directories, is to add the directory or directories containing
these m-files to the search path.
path
You can add the directories mydir1, mydir2, etc. to the old path with the
command: addpath mydir1 mydir2 etc.
Unfortunately, when you quit your current MATLAB session, your additions to the
path are "forgotten." If you always start your new MATLAB sessions from the
same working directory, you can use your text editor to create an m-file titled
startup.m in that directory which MATLAB automatically executes when it starts.
In that m-file, put the line addpath mydir1 mydir2 etc.
In MATLAB, if you know the name of a command, you can get information about
it by entering: help command_name at a prompt. If you enter: help path or
help addpath you will find more detailed instructions on the use of these
commands as well as examples of adding file names to paths for a variety of
computer systems including Unix, Windows/DOS, and Macintosh.
MATLAB Tutor
dy/dt = y (1 - y)
and to check the solution. Then we will adapt the solution procedure to an initial
value problem with this same differential equation. In the next part, we will relate
these algebraic calculations to the geometry of direction fields.
1. First declare the variable t as symbolic and give the differential equation a
name by entering:
syms t
DE1 = ' Dy = y*(1 - y) '
ysol = dsolve(DE1)
pretty(ysol) % Gives nice format
Then use your solution expression ysol to find an explicit formula in t for
y(1 - y). Is this formula the same as the one for dy/dt? You may want to
simplify the output before you try to answer this.
3. Now we add the initial condition y(0) = 1/10 to determine a single solution
of the differential equation. To tell MATLAB to solve the initial value
problem, put both parts of the problem -- the differential equation and the
initial condition -- into dsolve. Enter:
subs(h, t, 0)
MATLAB Tutor
2. In order to make the plot of the direction field, the "slpfield" function must
be provided a function called "dfun" which gives the right hand side of the
differential equation.
Use a text editor to edit the file dfun.m (provided in the same package as
slpfield.m) so that the right-hand-side function is y.*(1-y). (The period after
the y is important.)
3. Assuming you have the correct dfun.m file, we can now plot the vector
field on the interval -2 < t < 2 and -0.5 < y < 2. Enter:
slpfield(-2, 2, -0.5, 2)
hold on %holds the plot
4. Now plot the function h from Part 12 on top of the slope field plot. We use
the same limits on t. Enter:
ezplot( h, [-2,2] )
axis( [-2, 2, -0.5, 2] )
5. Adjust the horizontal ranges and redraw the direction field and the solution
plot so that you can see the solution function h approach equilibrium. If
necessary, enlarge the picture so you can see more detail. Are you
convinced that the symbolic solution h fits the direction field?
6. Edit the dfun.m file in order to generate direction fields over appropriate
ranges of the variables for the following differential equations:
o dy/dt = y2
o dy/dt = ty + t