MATLAB, a product of Mathworks, is a software widely used
for exploring, refining, and understanding the numerical algorithms used in
many scientific and technological fields.
Engineers nowadays can hardly survive without the use of MATLAB as a
test platform for their codes. Useful
applications in different fields include processing of medical images, stress
and strain study in structural mechanics, earthquake data analysis in seismology,
reaction-diffusion processes in ecology and kinetic chemistry, and Markov
processes in mathematical economy.
MATLAB, an acronym for MATRIX LABORATORY, is also very efficient at
visualizing pure mathematical problems.
Complicated non-linear equations, differential and integral equations,
and evaluation of integrals can all be solved numerically, and to a good extent
MATLAB is mainly a programming language. However, in contrast to many programming
languages, MATLAB is extremely easy to use.
It is flexible to the userís needs and requires almost no so-called
ďprogramming skills.Ē For the expert,
MATLAB is an interpreted language but can also be translated to C or C++ code
if desired. We will not discuss this
advanced topic in this session.
This class provides you with basic manipulations and
techniques for the use of MATLAB. It is
assumed that you have some knowledge of elementary Calculus and that you know
the concept of vector (although we will give a brief review of it). This tutorial is intended for MATLAB on a
PC/Windows workstation, but if you need information about Macs or Unix, do no
hesitate to ask.
This course lasts for three hours and is structured into
three parts. There will be two breaks
of five to ten minutes each hour.
Please stop the
instructors and ask for explanations if something is not clear or is not
MATLAB Course Outline
Part 1: Elementary Steps
Up and Closing Down
Operations (dot notation)
8. Matrix and Vector Functions
Part 2: Graphics, Output Format, and
Programming with MATLAB
2. Loops and Conditions: For, While, If Loops
Part 4: Managing
1. Printing and
2. Saving and loading
3. Submitting MATLAB
Part 1: Elementary Steps
1. Starting Up and Closing Down
How to Start?
MATLAB can be used in both interactive and silent
modes. During this class we will be
operating in the more commonly used interactive mode.
If you are on a Windows workstation, click on
button. A pop-up menu will fly
out. Select successively Programs, Applications,
and then MATLAB 5.3.
If you are on a different PC, click on Start, then Find
(Files or Folders) and look for MATLAB through the dialog
window. Double click on the MATLAB
After some loading time (usually 10 to 30
seconds), the MATLAB Command Window will appear. The command window in MATLAB is referred to as the shell.
You will see the following output on your shell:
started, type one of these commands: helpwin, helpdesk, or demo.
For information on all of the MathWorks
products, type tour.
This is MATLAB's greeting as the program begins.
Remark: Always check the Version number when
you are using MATLAB on a different network. This can be done by typing:
How to End?
You can end a MATLAB session with the command
will also work. Either one of these
commands will bring you back to the shell prompt.
Asking for Help
MATLAB Online Manual
There are several ways for getting help with
MATLAB. A good way to start is to type:
The helpdesk command opens an HTML document, which contains the MATLAB
reference book. This is quite a large
documentódonít be overwhelmed! Useful
sections for beginners include Getting
Started and MATLAB Functions. You might want to browse them before
beginning your first session.
Itís helpful to keep this browser window open while you are working with
MATLAB, so that you can refer to it easily.
Other Sources of Help
There are other ways of getting help with MATLAB
that do not make you search through the whole reference book. If you already know the name of a MATLAB
Function--for example, quit--and you want to
learn about its use, enter:
You will see a description of the command quit.
During your first experiences with MATLAB you
should from time to time take a:
session which will show you various features of
Another very useful feature is the lookfor
command. It looks for all the commands related to a given topic. Try:
will list all of the commands we just discussed.
Command Line Editing
Once you open a MATLAB session, you start
entering command lines. A command line consists of one or more statements separated by a
semicolon. A statement is defined as "the smallest executable piece of
We already saw some examples of command lines
above, other examples are:
(which extracts the square root of 2 and returns
it as an output)
A = sqrt(2);
(this assigns to the variable A the
value of square root of 2).
When you enter the command lines the >> should not be
typed in. This is not part of the command line, but rather indicates its
Every command line terminates with a <return>
(or <enter> if you prefer).
MATLAB has very flexible syntax, and the same command line can be entered in
different ways. We will discuss this
A single command line can contain more statements. For example:
B = 3;
Notice that the <return> should
be typed in only at the end of the command line.
The use of the semicolon
If you tried to type in the three command lines
above you may have noticed some differences in MATLABís reaction to them. For
furnishes the output:
whereas the command line:
A = sqrt(2);
seems to have no effect. Actually it has, but we
do not see the effect because of the semicolon ";"
at the end of the command line. The
semicolon is a request for MATLAB not to show the outcome of the operation.
This is useful in programs when MATLAB performs a lot of intermediary
The command line above is an assignment
operation. To make sure that MATLAB performed it just type in:
and the output should read:
This would have been the output of the command
line defining A if we hadn't typed the semicolon at the
end of the command line.
Recalling old command lines
During a MATLAB interactive session it is
possible to recall one of the former command lines by typing <arrow up> as many times as needed
to reach the desired line. This feature can save a lot of time, especially if a
simple command line must be repeated many times. The <arrow down> key will scroll down the history of command
Try this command to recall what you have entered
in your MATLAB session so far.
Stopping MATLAB calculations
Often one needs to interrupt MATLAB while it is
computing. This is done by typing
at the same time.
When creating a large matrix, it is useful to
name it with a variable name.
Upper or lower case letters can be used to form
a variable name. They can contain
digits, but not in the first position. All other characters (space included)
are not allowed in variable names. The only non-alphanumeric character that is
allowed is the underscore "_"
which is used in accordance to tradition as a space since the latter is not
Legal choices for variable names in MATLAB are M , m , A ,
etc. Notice that some of these,
although legal, are not really aesthetic.
The following are illegal choices for variable
names in MATLAB: 2 , #2 , a#
A , w@1 , w1,2 , f'
MATLAB distinguishes between upper and lower case letters! All the variables above are different.
To use variables, we type the variable name
followed by an equals sign, followed by what we want that variable to
represent. For instance:
And the computer will respond with:
There are a few commands that make managing the
variables you use easier.
will list the variables you have used:
While the command:
will list the variables you have used, along
with some other pertinent information, including the size of the matrix that
the variable represents, the type of variable, and the amount of memory taken
up by that variable:
A 1x1 8 double array
myvariable 1x1 8 double array
Grand total is 2 elements using 16 bytes
* Remember, MATLAB stores ALL variables as
matrices, including single numbers (which are recorded as 1x1 matrices).
Finally, if we want to clear one or all of our
variables, we use:
to clear all of our variables we have used.
If we want to see what a variable is designated
as, we type the variable name:
There is one other type of variable we will be
discussing later in the class, which is the 'symbolic variable.' Using symbolic variables, we are able to
solve equations symbolically instead of numerically.
4. Matrices and Vectors
The basic data structures that MATLAB uses are
objects known as matrices. A matrix
is a rectangular table consisting of numbers. These numbers are referred to as entries or elements of the matrix. Matrices are very handy objects widely used
in mathematical applications and are very simple conveyors of information. An
example of a matrix is:
1 3 4 5
-1 0 2 2
-1 -1 1
Since this matrix has three rows and four
columns, it is referred to as a 3x4 (three by four)
The entries of a matrix have their position
identified by the number of the column and the number of the row they sit in.
For example, in the matrix above, the [3,2] entry is -1, and the [2,3] entry is
To enter the above matrix in MATLAB we type:
M = [1 3 4 5; -1 0 2 2; 1 -1 -1 1]
M = [1 3 4 5
-1 0 2 2
0 2 2 2]
MATLAB provides a lot of different ways for
generating matrices and vectors. Some are built-in functions. Try the following
Noise = rand(4)
diag([1 4 5 6 -1])
I = eye(3)
There are many other built-in matrix building
functions, and as you become more expert you will be able to define your
When you enter matrices you are not required to assign a variable name to them.
Although this can sometimes be useful (such as when you try new commands), it
is poor practice when effectively using MATLAB.
Since vectors form a particular subclass of matrices,
all that has been said about matrices applies to vectors (with the appropriate
restrictions). For example:
will construct a row vector of length 3 whose
entries are zeros.
However, an easier way to build vectors is by
using the colon " : "
The colon builder has two required arguments:
the starting point and the ending point.
For example, the following command line:
v = 1:9
2 3 4 5 6
7 8 9
The colon builder can be made more sophisticated
by adding a third (optional argument) between the starting and ending point.
This argument indicates the stepsize.
w = 1:0.5:9
Columns 1 through 7
1.5000 2.0000 2.5000
3.0000 3.5000 4.0000
Columns 8 through 14
5.0000 5.5000 6.0000
6.5000 7.0000 7.5000
Columns 15 through 17
The output of the last example looks quite different from the previous one.
There are two reasons for this:
The vector v consisted solely of integer entries.
This makes MATLAB output its entries in the integer format, while the entries
of the vector w are in floating point format. The floating point format is how computers
understand what we usually call decimal numbers. Sometime these are incorrectly
called real numbers.
The vector v is shorter than w, and MATLAB was able
to write it out in one single line. This type of output was not possible for
the vector w because the screen is too small, and the
row vector was thus split into several lines. However, since these several
lines still represent a single row, MATLAB indicates this fact by appending the
" label above each line.
Accessing and manipulating entries
Consider the matrix:
and suppose that we are interested in accessing
the entry sitting in row 2 and column 3 (the value being 4). We type in:
Notice the way we entered the matrix M, using commas and
Access the entries (1,2), (2,1) and (4,1) of the matrix M
The entries of a matrix can also be modified.
Set the entries (1,2) and (2,1) of to -12 and 56, respectively.
We can also access the entries of a matrix not
only individually but also in blocks (called submatrices). Assume for example
that we are given the matrix:
A = rand(4)
then if we wanted to remove the 3x3 matrix
consisting of the first three rows of the last three columns, we would type:
B = A(1:3,2:4)
To get the second row or fourth column of A
we enter, respectively:
second_row = A(2,:)
fourth_col = A(:,4)
This syntax can be used also to modify the
entries, for example:
A(1,:) = 1:7
A(:,1) = (1:7)'
Matrices, vectors and scalars can be added,
subtracted and multiplied. Scalars can be divided, and we will see that
matrices and vectors can also be divided.
Operations on scalars with MATLAB resemble those
performed by pocket calculators. Here are some examples to try:
a = 4; b = 5; c = a*b
c = c+1
The last statement may look like nonsense to those who are not used to computer
programming languages. Indeed, if you consider that statement as a mathematical
equality, it is impossible to find a number c
that equals itself plus one. However, in MATLAB and most of the computer
languages, the sign " =
" does not mean equality but means
assignment. The last statement makes MATLAB perform the following logical
sequence of operations:
the current value of the variable c;
1 to this value;
the result as a new value for c.
Two matrices, M1
can be summed and subtracted but they must meet the
number of columns of M1 must equal the number of columns of M2, and
number of rows of M1
must equal the number of rows of M2.
In particular, two row vectors can be added (or
subtracted) if they have the same length and column vectors can be added (or
subtracted) if they have the same size.
Here are some examples to try:
A = A + B
u=[1 2 3 3 2 1]
A useful matrix function that helps us to
understand if two matrices can be summed is the size function. For example:
The first output tells us that u has 1 row and 6
columns, while the second output tells us that v has 1 row and 7 columns. We cannot sum these two vectors!
Row-by-Column Matrix Multiplication
We will not go into the details of Matrix
Algebra. This is a topic that is covered in elementary courses of Linear Algebra
like MATH240 at UMCP. If you have never seen matrices before today, then the
next paragraph might be a little confusing to you. Nevertheless you should make
an effort to follow; things will become clearer when you encounter matrices in
Suppose you want to multiply M1 by M2. These
must first meet the
product compatibility requirement
number of columns of M1 must equal the number of rows of M2.
It can happen that the product M1*M2
is defined while M2*M1 is not defined. Even when both products
are defined they are not necessarily equal.
Here is a series of allowed and not allowed
M1=[1 2 -1
3 4 5];
>> M2=[2 -1
Which operations werenít possible? Why?
In the last example we could have shortened the
The power operation on a matrix is just a
shortcut for repeated (matrix) multiplication, exactly as with scalars.
The transpose operation is a basic matrix
manipulation which is input in MATLAB by affixing a single quote "'".
This operation interchanges the row index with the column index.
The inner product of two spatial vectors v and w described in an
orthonormal reference frame as v=(vx,vy,vz), w=(wx,wy,wz)
is defined as the scalar:
= (vx wx)+(vy wy)+(vz wz).
Given the vectors (1,2,3) and (-2,1,3), compute
their inner product by using matrix operations of MATLAB.
Given a matrix M1
and a scalar a, we can multiply M1*a
and a*M1. The result is a matrix whose entries are the
entries of M1 each multiplied by a.
a = ; M1
the above example even though a is entered as a
matrix, MATLAB treats it as a scalar. The use of the square brackets is
redundant and is put only to emphasize this observation. Normally one would
type just " a = 3 ".
scalar-by-matrix multiplication is commutative, unlike the row-by-column matrix
operation above is referred to sometimes as scaling
the matrix M1
Notice that the scaling of the matrix acts entry-wise unlike the row-by-column
multiplication. The scaling of matrix is called an array operation because of this behavior.
What about scalar-by-matrix addition?
What happens if you type in the following
c = 1000; f = [1 3 -1 4]; c+f
Investigate the division of matrix by a scalar.
Matrix division: solving linear systems
system is a problem of the type:
Given an n x n matrix A and a (column) vector b of size n, for which (column) vector x
of size n is the equation Ax = b satisfied?
By basic linear algebra it is known that if A is non-singular (i.e., if det A is non zero), then this system admits
one and only one solution x. It is
extremely easy to compute this solution using the left division command in
A = [ 1 2 3
3 0 0
0 1 -1];
b=[1 1 -2]';
Note that in the above example we used a backslash division bar " \
" as opposed to the traditional division bar " /
". One can use the right division operator " /
" to solve the "row type" linear system:
Given an n x
matrix B and a (row) vector r of length n, for which (row) vector y
of length n is the equation yB = r satisfied?
This comes from the fact that matrix
multiplication is NOT commutative, unlike scalar multiplication, which is.
This new system is solved by typing:
>> y = B/r
Given an n x n matrix A and column vector b
of length n, what is the difference
x = (b'/A')'
x = A\b
Most of MATLAB commands are functions. Some of these functions represent mathematical functions
and operate on scalars as well as on matrices. Typical examples of scalar
functions are the traditional elementary functions from basic calculus:
This last one is just the absolute value
function applied to -15, denoted usually by |15|.
Other examples of less traditional scalar
important remark: All scalar functions operate on matrices
entry-wise. Matrices are viewed as
arrays of numbers, and the function operates on every entry independently of
the other entries. The output of a scalar function with matrix input (say of
size n xm) is another matrix of
the same size (n xm).
A = [1 4
W = [10.334 12.307 -13.554 14.306]
12.3070 -13.5540 14.3060
1 -1 1
This feature of MATLAB makes it very easy to
construct tables of function values as shown by:
What do you expect the outcome of the following command line to be?
A=[1 4; 16 25];(sqrt(A))^2
Array Operations (dot notation)
The last exercise can be puzzling. Indeed, we
expect that taking the square root of an object and then squaring the result
will recover the original object. This works if the object is a scalar, but in
the case of matrices some extra caution is needed. Consider the matrix:
M = [1 2;3 4]
and suppose we want to square each element of
the matrix. From what we have seen in the matrix operation section, if we
we do not obtain the desired result, but rather
the result of the operation M*M . To force MATLAB to
perform an entry-wise operation we use the dot
Try these other examples:
Z = [1 3 ; 4 1]; Y = [-2 3 ; 4 -5];
What do you expect the outcome of the following command line to be?
A=[1 4; 16 25];(sqrt(A)).^2
Matrix and Vector Functions
In MATLAB, there are functions that operate on a
matrix as a whole. In contrast to scalar functions applied to matrices, the
output of matrix functions can be a different type of matrix than the original
one. Important matrix functions are:
(already discussed above)
Some matrix functions, like det,
operate only on square matrices; and some functions, like rank
operate on any type of matrix (a matrix is square
when the number of rows equals the number of columns).
Besides scalar functions and matrix functions,
there is an intermediate class of functions: the vector functions that operate on vectors (either row or column).
The following examples illustrate some of these functions. First construct randomly a vector:
v = 10*rand(1,10);
we can have optimization type functions:
or algebraic functions:
or statistical functions:
What do you expect the outcome of:
If the operand of a vector function happens to
be a matrix, then the function operates column-wise. That is, it considers every column as a single vector, and
returns a row-vector containing in each column the result of the function on
the corresponding column. It is clearer with an example:
free to ask the trainers for explanations!
the following matrices
1 2 -1
and perform the
following operations if they are possible (avoid error messages):
C=AB, D=BTAT ,
det(C), det(A), find the spectrum (eigenvalues) of D.
the vectors v = (1, 2)T and w = (1, 3, -1), decide which of the
following operations are legal (avoiding error messages as much as possible)
and perform them:
x = wB, y = AwT, z = Bv, u = vA.
the cube function on the interval [-4, 4]. Try this exercise with three
different step sizes: say 0.1, 0.01 and 0.001.
the linear system:
12 x + 4 y + 3 z = 1
3 x + 2 y = -1
2 y - 4 z = 9
To do this you should
first write it down in a matrix form, and then use the matrix division
two column vectors of length 20 with random entries between 0 and 100. Sort the
first vector in ascending order and find a method to sort the second in
descending order. (Hint: scaling by (-1) inverts the order of the numbers.)
the two vectors and find the median of their sum.
Part 2: Graphics, Output Format, and
Two Dimensional Graphics
The plot function
Suppose x and y are two vectors of same length,
the command line:
produces a graph of the elements of x versus the
elements of y. If the elements of x are in ascending order and distinct, then
the graph is similar to that of a mathematical function. Otherwise the graph
might be more complicated. For example:
x = -3:.1:3; y = x.^3; plot(x,y);
will plot the graph of the cube function on the
If you want to plot a parametric curve, a
cardioid for instance, start by setting up a parameter vector:
t = 0:pi/30:2*pi;
and then give the parametric equations for the
abscissa and ordinate as the arguments of plot:
plot( (1-cos(t)).*sin(t) , (1-cos(t)).*cos(t) );
We don't have to plot necessarily mathematically
defined functions. We can also represent results from experimental data: for
example, the average maximal temperature of each month last year.
months = 1:12;
In the last example, however, we can simplify
Indeed, if only one argument is given, it is
considered as a second argument of a plot command, while the first argument is
taken to be the correspondent index vector.
Notice that the output of the plot function does not appear in the MATLAB
shell, it appears in a graphics
window. Clicking first on the File menu and then selecting the Close option
will close this window.
The plot function accepts optional arguments to
control the plotting style. For
x = -3:.1:3; y = x.^3; plot(x,y,'o')
will put circles at the data points; and:
x = -3:.1:3; y = x.^3; plot(x,y,'g-.')
will plot a green dashed-dotted line.
Embellishments and information in plots
We can add some labels to the picture, for
text(-2,20,'Is this a green function or a Green function?')
A useful command is the so called interactive text positioning:
t = 0:pi/30:2*pi;plot( (1-cos(t)).*sin(t) , (1-cos(t)).*cos(t) );
gtext('This spot is hot!')
Other simple plotting commands
In addition to the command plot,
MATLAB furnishes many variations. For example:
draws a bar graph:
theta = 0:pi/12:2*pi;polar(theta,2*(1-cos(theta)));
draws a polar graph:
One easy thing to do in MATLAB graphs is to increase the resolution of your
graph. For example, if you are not satisfied with the output of the last
theta = 0:pi/36:2*pi;polar(theta,2*(1-cos(theta)));
Plotting more than one graph on the same plot
Sometime we would like to compare two graphs on
the same picture. There are three different ways of doing this with MATLAB.
Suppose we want to compare exp to its Taylor expansion of order 2, 1+x+(1/2)x2, and to that of order
Define singularly the vector of values
corresponding to each function:
Notice the use of the dot notation.
Define a matrix whose columns are the vector of
values of the functions:
(Graph should be
the same as above)
Notice the use of the prime notation.
MATLAB automatically chose the colors for the graphs to be traced with. In
the first method, however, we can enter the
We can also choose to draw each graph in a
different line-style for black and white printing purposes by entering:
Combine different colors with different line-styles.
Third method (the hold command)
This method is substantially different (and more
general) than the first two. It makes use of the command hold, which freezes (holds) the current picture. To defrost
(release) the picture use hold again. Example:
Another example, which illustrates the
generality of the hold command, is the following:
To emphasize the fact that the plots of MATLAB
can represent more than mere functions graphs, try the following example of
reporting the typical data of a repeated experiment with one parameter.
In this example we have used the colon
which means the n-th column of the
. Analogously, if we were to write M(n,:) for some matrix M
and some number n, this would extract
the n-th row of M
You might have already heard of software like MATHEMATICA
(R) or MAPLE
(R). These are the two most widely used examples of symbolic computation software. As opposed to this type of software,
MATLAB is a numeric computation software.
Nevertheless, MATLAB is able to perform symbolic computations: in fact MATLAB
relies on MAPLE
(R) in order to perform the symbolic computations.
Symbolic computations are those computations
that involve symbols (the symbols can be any valid MATLAB variable names). Let
us do two examples.
Creating Symbolic Expressions
First we need to declare which will be our
syms a b c d x y z
then we proceed as if these symbols were actual
numbers in floating point notation or MATLAB variables:
A= [a b; c d]
Creating Symbolic Functions
We can define a function f symbolically as an expression:
f = 1 + 2*x^2 + cos(x)
We can compute the derivative of f using the command diff:
assign this new expression to another variable:
and take successive derivatives:
To find the antiderivative (primitive, or
indefinite integral) of f type in:
and for the definite integral, between 0 and 2
for example, enter:
Solving equations symbolically
We can also solve symbolically algebraic
equations. For example, consider the quadratic equation:
a x2 + b x + c = 0.
This can be solved by the following sequence of
syms x a b c
p = a*x^2 + b*x + c
Notice that we obtain two solutions in the form
of a vector.
If nothing is specified, the symbol x is considered to be
Consider the equation:
ln (y) - ln (r-y) = k t + C
where r, k
and C are constants, t is a parameter and y is the unknown. To solve for y, type:
syms r k C t y
equation = 'log(y) - log(r-y) = k*t + C'
Since the solution is one (unlike the quadratic
case), we can solve and assign:
y = solve(equation,y)
Now y is an expression and
we can exploit it. If we wish for example, we can solve the equation:
y = 5
Solving Differential Equations
We can use the function dsolve to solve symbolic
To solve the following equation:
We need first to make sure y is a symbolic
Then we use dsolve to solve the equation:
Notice that D is the differential operator (in
other words, Dy means the derivative of y).
As well, this equation gives a family of solutions, with C1 as the
If we want to put initial conditions, we just
add them as additional arguments of the function dsolve:
the following graphs in the (x,y)-plane:
y = sin (x), for x in [-2 pi, 2 pi];
y = arctan (x), for t in [-10,10];
x = y3
+ ey, for x in [-2,7].
the following data in a matrix form and then produce a pertinent plot of the
height (inches) 62 80 67 72 76 67 73 79 67 69 72 70 64 69 73 71 61
(lbs.) 110 180 120 151 160 123 155 158 123 147 166 156 108 152 170 175 103
symbolically the equation:
3: Programming with MATLAB
MATLAB is mainly a programming language. The
power of MATLAB lies in its flexibility, adaptability and ease in programming.
What requires hours of planning and implementing (not to speak of debugging!)
in C/C++ or Fortran can be done in minutes with MATLAB.
is the mysterious sounding name for any sequence of MATLAB commands that is
stored into a file. There are three
general types of M-files that you may find useful. The first is a 'Data M-file'.
In it you store the variables, constants, and matrices that you are
using during your MATLAB session. The
second, which we will discuss here, is called a 'Script M-file'. It stores a series of commands which are
executed by MATLAB when you type the filename of the M-file. Storing sequences of commands is handy when
the same sequence is to be used many times.
Let us focus on a concrete example:
We would like to plot the graphs of the
functions fn (x) = xn e-nx on the interval [0,20] for all
integers n between 1 and 30.
We could use plot and hold, but we would have to
type in almost the same command line thirty times... Can we do something
better? Yes, we are going to edit an m-file that performs the task. To this end
we must first open an editor. This can be done from within the MATLAB shell by
and this should open the MATLAB editor/debugger.
Now let us type in the editor buffer the following script:
Save this file as first.m
and come back to the MATLAB shell. Finally, enter the command line:
NOTICE: You might have problems with this
because your path is not set
correctly. The path is a collection of directories (folders) where MATLAB goes
to look for programs to be run. If you saved that file first in, say, Myfolder,
you should tell this to MATLAB by typing:
or opening the path browser utility from your
The third type, the function M-file, is by far
the most powerful in MATLAB. The M-file
will be discussed in the Intermediate Class in some depth, since it is an
important aspect of MATLAB.
Before we move on to the last topic in our
class, letís take a look at one command in particular which may be found useful
in script files.
2. Loops and
Conditions: For, While, If Loops
A for loop will execute the commands within that
loop for each value of the index in the for command. As in the example above, we executed the function for various
values of n and then plotted each of those graphs. For loops are a powerful shorthand for doing things that are
nearly the same over and over.
The next example will illustrate the for-loop
We will construct a script m-file. The Fibonacci
sequence is defined by the recursion:
an+1 = an + an-1,
for n = 1, 2, ...
The first two terms (starting values or seeds) a0 and a1 are usually prescribed numbers.
Classically, the Fibonacci sequence starts with:
a0 = 1 and a1 = 1.
It is a well known fact that:
lim an+1/an = (1 + sqrt(5))/2, as n tends to infinity.
(The golden ratio.)
The following script will compute the 100th term
of the Fibonacci ratio sequence:
a = a1+a0;
a0 = a1;
a1 = a;
Remember: you must save this and then run it
from the shell by typing in the name of the file you gave it.
4: Managing MATLAB
Printing and Exporting
We obviously must be able to print the graphical
output. There are several ways of doing this.
The simplest one consists in using the menubar of the output window:
click on File and then on Print...
Another way of printing is to use print
. To print the current plot just enter print .
A plot however can also be print-ed
(or exported) to a file. Examples of this are:
print -dps2 snapshot
which will generate a PostScript (*) file named snapshot.ps .
[(*) PostScript (ps) is a standard format for
printable graphic objects];
print -dpsc2 snapshot
will generate a color PostScript file;
print -djpeg snapshot
will generate a jpeg (*) file named snapshot.jpg
or snapshot.jpeg .
[(*) JPEG (or JPG) is a popular format for
pictures that is "understood" by most internet browsers.]
Saving and loading MATLAB sessions
We have seen how to save the pictures that are
produced by MATLAB. What about saving the results of a computation? It is not rare that one has to save a 1000
by 1000 matrix: i.e., one million numbers!
To save the variables that are in use in a session we use save. For example, suppose you want to save all
the variables of your session then:
will save your data in a file named sess1. If
you only want to save certain variables (e.g., A B Q m z) then you just need to
list them after the name of the file:
save sess1 A B Q m z
To retrieve these variables in some other
session we enter:
Submitting MATLAB work
The neater the assignment, the happier the
teacher. MATLAB offers an easy way for turning in organized and readable work.
Here are some tips.
Use the diary command:
All the input and output of your session will be
saved in a file named results.
If there are some parts you don't want to save,
then before them type:
You can switch the diary on again by typing:
Before turning in the assignment you can (should!)
edit the diary file (results, in our example) by inserting your own
comments as a text. Use it also to add embellishments in your graphs, write
labels, and put information wherever you think it is appropriate.