Chapter 1
Chapter 1
The computational examples and exercises in this book have been computed using Matlab, which is
an interactive system designed specifically for scientific computation that is used widely in academia
and industry. At its core, Matlab contains an efficient, high level programming language and
powerful graphical visualization tools which can be easily accessed through a development environ-
ment (that is, a graphical user interface containing various workspace and menu items). Matlab
has many advantages over computer languages such as C, C++, Fortran and Java. For example,
when using the Matlab programming language, essentially no declaration statements are needed
for variables. In addition, Matlab has a built-in extensive mathematical function library that con-
tains such items as simple trigonometric functions, as well as much more sophisticated tools that
can be used, for example, to compute difficult integrals. Some of these sophisticated functions are
described as we progress through the book. Matlab also provides additional toolboxes that are
designed to solve specific classes of problems, such as for image processing. It should be noted that
there is no free lunch; because Matlab is an “interpreted” language, codes written in Fortran and
C are usually more efficient for very large problems. (Matlab may also be compiled.) Therefore,
large production codes are usually written in one of these languages, in which case supplementary
packages, such as the NAG or IMSL library, or free software from netlib, are recommended for scien-
tific computing. However, because it is an excellent package for developing algorithms and problem
solving environments, and it can be quite efficient when used properly, all computing in this book
uses Matlab.
We provide a very brief introduction to Matlab. Though our discussion assumes the use of
Matlab 7.0 or higher, in most cases version 6.0 or 6.5 is sufficient. There are many good sources
for more complete treatments on using Matlab, both on-line, and as books. One excellent source
is the MATLAB Guide, 2nd ed. by D.J. Higham and N.J. Higham published by SIAM Press, 2005.
Another source that we highly recommend is Matlab’s built-in help system, which can be accessed
once Matlab is started. We explain how to access it in section 1.1. The remainder of the chapter
then provides several examples that introduce various basic capabilities of Matlab, such as graph
plotting and writing functions.
1
2 CHAPTER 1. GETTING STARTED WITH MATLAB
• On a Macintosh running OS X 10.1 or higher, there may be a “Matlab” icon on the dock.
If so, then clicking this icon should start Matlab. If the “Matlab” icon is not on the dock,
then you need to find where it is located. Usually it is found in /Applications/$MATLAB/,
or /Applications/$MATLAB/bin/, where $MATLAB is the name of the folder containing the
Matlab installation. Once you find the “Matlab” icon, double clicking on it should start
Matlab.
• On Unix or Linux platforms, typically you enter matlab at the shell prompt. That is, you
open a terminal, and enter the command matlab.
When you have been successful in getting Matlab to start, then the development tool Graphical
User Interface (GUI) should appear on the screen. Although there are slight di↵erences (such as
key stroke short cuts) between platforms, in general the GUI should have the same look and feel
independently of the platform.
The command window, where you will do much of your work, contains a prompt:
>>
We can enter data and execute commands at this prompt. One very useful command is doc, which
displays the “help browser”. For example, entering the command
>> doc matlab
opens the help browser to a good location for first time Matlab users to begin reading. Alternatively,
you can pull down the Help menu, and let go on MATLAB Help or Documentation. We recommend
that you read some of the information on these help pages now, but we also recommend returning
periodically to read more as you gain experience using Matlab.
Throughout this book we provide many examples using Matlab. In all cases, we encourage
readers to “play along” with the examples provided. While doing so, it may be helpful at times to
use the doc command to find detailed information about various Matlab commands and functions.
For example,
is a matrix with 3 rows and 4 columns, and so is typically referred to as a 3 ⇥ 4 matrix. It is two-
dimensional. The values in the matrix are by default all Double Precision numbers which will be
discussed in more detail in the next chapter. This fact permits Matlab to avoid using declarations
but involves a possible overhead in memory usage and speed of computation. A matrix with only
1.2. BASICS OF MATLAB 3
one row (that is, a 1 ⇥ n matrix) is often called a row vector, while a matrix with only one column
(that is, an n ⇥ 1 matrix) is called a column vector. For example if
2 3
2
6 8 7
6 7 ⇥ ⇤
x=6 6 4 7
7 and y = 3 6 3 4 ,
4 0 5
5
then we can say that x is a 5 ⇥ 1 matrix, or that it is a column vector of length 5. Similarly, we can
say that y is a 1 ⇥ 4 matrix, or that it is a row vector of length 4. If the shape is obvious from the
context, then we may omit the words row or column, and just refer to the object as a vector.
Matlab is very useful when solving problems whose computations involve matrices and vectors.
We explore some of these basic linear algebra manipulations, as well as some basic features of
Matlab, through a series of examples.
Initializing Vectors. We can easily create row and/or column vectors in Matlab. For example,
the following two statements create the same row vector:
>> x = [1 2 3 4]
>> x = [1, 2, 3, 4]
Similarly, the following two statements create the same column vector:
>> x = [1
2
3
4]
>> x = [1; 2; 3; 4]
Rather than thinking of these structures as row and column vectors, we should think of them as
1 ⇥ 4 and 4 ⇥ 1 matrices, respectively. Observe that elements in a row may be separated by using
either a blank space or by using a comma. Similarly, to indicate that a row has ended, we can use
either a carriage return, or a semicolon.
Initializing Matrices. In general, we can create matrices with more than one row and column.
The following three statements generate the same matrix:
>> A = [1 2 3 4
5 6 7 8
9 10 11 12]
>> A = [1 2 3 4; 5 6 7 8; 9 10 11 12]
>> A = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12]
Matrix Arithmetic. Matrices can be combined (provided certain requirements on their dimensions
are satisfied) using the operations +, -, * to form new matrices. Addition and subtraction of
matrices is intuitive; to add or subtract two matrices, we simply add or subtract corresponding
entries. The only requirement is that the two matrices have the same dimensions. For example, if
2 3 2 3
3 1 7 3
3 2 2
A=4 3 2 5, B = 4 2 2 5 , and C =
5 8 2
3 0 3 1
then 2 3 2 3 2 3 2 3
3 3 4 40
c1 a 1 + c 2 a 2 + c 3 a 3 = 9 4 4 5 + 34 8 5 + 14 0 5 = 4 60 5 .
2 0 4 14
is a linear combination of the vectors a1 , a2 and a3 with the scalars c1 , c2 and c3 , respectively.
Now, suppose we define a matrix A and column vector x as
2 3 2 3
3 3 4 9
A = 4 4 8 0 5, x = 4 3 5,
2 0 4 1
then the matrix–vector product Ax is simply a compact way to represent a linear combination of the
columns of the matrix A, where the scalars in the linear combination are the entries in the vector
x. That is, 2 3 2 3 2 3 2 3
3 3 4 40
Ax = 9 4 4 5 + 3 4 8 5 + 1 4 0 5 = 4 60 5 .
2 0 4 14
Thus, to form Ax, the number of columns in the matrix A must be the same as the number of entries
in the vector x.
Finally we consider matrix-matrix multiplication. If A is an m ⇥ n matrix, and B is an n ⇥ p
matrix (that is, the number of columns in A is the same as the number of rows in B), then the
product C = AB is an m ⇥ p matrix whose columns are formed by multiplying A by corresponding
columns in B viewed as column vectors. For example, if
2 3 2 3
3 3 4 9 1 2 0
A = 4 4 8 0 5 and B = 4 3 0 1 3 5
2 0 4 1 2 1 5
then 2 3
40 5 7 11
C = AB = 4 60 4 0 24 5 .
14 10 0 20
1.2. BASICS OF MATLAB 5
So, the jth column of AB is the linear combination of the columns of A with scalars drawn from the
jth column of B. For example, the 3rd column of AB is formed by taking the linear combination
of the columns of A with scalars drawn from the 3rd column of B. Thus, the 3rd column of AB
is ( 2) ⇤ a1 + (1) ⇤ a2 + ( 1) ⇤ a3 where a1 , a2 and a3 denote, respectively, the 1st, 2nd, and 3rd
columns of A.
The ⇤ operator can be used in Matlab to multiply scalars, vectors, and matrices, provided the
dimension requirements are satisfied. For example, if we define
>> A = [1 2; 3 4]
>> B = [5 6; 7 8]
>> c = [1; -1]
>> r = [2 0]
and we enter the commands
>> C = A*B
>> y = A*c
>> z = A*r
>> w = r*A
we find that
19 22 1 ⇥ ⇤
C= , y= , w= 2 4 ,
43 50 1
but an error message is displayed when trying to calculate z = A*r because it is not a legal linear
algebra operation; the number of columns in A is not the same as the number of rows in r (that is,
the inner matrix dimensions do not agree).
Suppressing Output. Note that each time we execute a statement in the Matlab command
window, the result is redisplayed in the same window. This action can be suppressed by placing a
semicolon at the end of the statement. For example, if we enter
>> x = 10;
>> y = 3;
>> z = x*y
then only the result of the last statement, z = 30, is displayed in the command window.
Special Characters In the above examples we observe that the semicolon can be used for two
di↵erent purposes. When used inside brackets [ ] it indicates the end of a row, but when used at
the end of a statement, it suppresses display of the result in the command window.
The comma can also be used for two di↵erent purposes. When used inside brackets [ ] it
separates entries in a row, but it can also be used to separate statements in a single line of code.
For example, the previous example could have been written in one line as follows:
>> x = 10, y = 3, z = x*y
The values x = 10, y = 3 and z = 30, are displayed in the command window. If the commas are
replaced by semicolons,
>> x = 10; y = 3; z = x*y
then only z = 30 is displayed in the command window.
The semicolon, comma and brackets are examples of certain special characters in Matlab that
are defined for specific purposes. For a full list of special characters, open Matlab’s documentation,
which can be done using the Matlab Help menu button, or by entering doc in the command window,
and navigate to: MATLAB > Language Fundamentals > Operators and Elementary Operations
> MATLAB Operators and Special Characters.
6 CHAPTER 1. GETTING STARTED WITH MATLAB
then 2 3
1 3
⇥ ⇤ 2
AT = 4 2 4 5, cT = 1 1 , rT = .
0
5 6
where superscript T denotes transposition. In Matlab, the single quote ’ is used to perform the
transposition operation. For example, consider the following matrices:
>> A = [1 2 5; 3 4 6];
>> c = [1; -1];
When we enter the commands
>> D = A’
>> s = c’*c
>> H = c*c’
we obtain 2 3
1 3
1 1
D=4 2 4 5, s = 2, H= .
1 1
5 6
Other Array Operations. Matlab supports certain array operations (not normally found in
standard linear algebra books) that can be very useful in scientific computing applications. Some of
these operations are:
.* ./ .ˆ
The dot indicates that the operation is to act on the matrices in an element by element (componen-
twise) way. For example, 2 3 2 3 2 3
1 5 5
6 2 7 6 6 7 6 12 7
6 7 6 7 6 7
4 3 5 .⇤ 4 7 5 = 4 21 5
4 8 32
2 3 2 3
1 1
6 2 7 6 8 7
6 7 6 7
4 3 5 .ˆ3 = 4 27 5
4 64
The rules for the validity of these operations are di↵erent than for linear algebra. A full list of
arithmetic operations, and the rules for their use in Matlab, can be found by referring to the
documentation (help), and navigating to: MATLAB > Language Fundamentals > Operators and
Elementary Operations > Arithmetic.
Remark on the Problems. The problems in this chapter are designed to help you become more
familiar with Matlab and some of its capabilities. Some problems may include issues not explicitly
discussed in the text, but a little exploration in Matlab (that is, executing the statements and
reading appropriate doc pages) should provide the necessary information to solve all of the problems.
1.3. MATLAB AS A SCIENTIFIC COMPUTING ENVIRONMENT 7
0, 0 + h, 0 + 2 ⇤ h, ··· , (i 1) ⇤ h, ··· , 1
We can create a vector with these entries, using the colon operator, as follows:
8 CHAPTER 1. GETTING STARTED WITH MATLAB
n = 101;
h = 1 / (n-1);
x = 0:h:1;
or, if we do not need the variable h later in our program, we can use:
n = 101;
x = 0:1/(n-1):1;
We often want to create vectors like this in mathematical computations. Therefore, Matlab provides
a function linspace for it. In general, linspace(a, b, n) generates a vector of n equally spaced
points between a and b. So, in our example with a = 0 and b = 1, we could instead use:
n = 101;
x = linspace(0, 1, n);
Note that, for the interval [0, 1], choosing n = 101 produces a nice rational spacing between points,
namely h = 0.01. That is,
⇥ ⇤
x = 0 0.01 0.02 · · · 0.98 0.99 1 .
A lesson is to be learned from the examples in this subsection. Specifically, if we need to perform a
fairly standard mathematical calculation, then it is often worth using the search facility in the help
browser to determine if Matlab already provides an optimized function for the calculation.
Problem 1.3.1. Determine what is produced by the Matlab statements:
>> i = 1:10
>> j = 1:2:11
>> x = 5:-2:-3
For more information on the use of ":", see doc colon.
>> rng(’default’)
>> R = rand(3,2)
What do you observe? Note: The “up arrow” key can be used to recall statements previously
entered in the command window.
Problem 1.3.4. Determine what is produced by the Matlab statements:
>> x = linspace(1, 1000, 4)
>> y = logspace(0, 3, 4)
In each case, what is the spacing between the points?
1.3. MATLAB AS A SCIENTIFIC COMPUTING ENVIRONMENT 9
Problem 1.3.5. Given integers a and b, and a rational number h, determine a formula for
n such that
linspace(a, b, n) = [a, a+h, a+2h, ..., b]
Example 1.3.1. Chebyshev polynomials are used in a variety of engineering applications. The j th
Chebyshev polynomial Tj (x) is defined by
In section 4.1.4 we see that these strange objects are indeed polynomials.
(a) First we plot, in the same figure, the Chebyshev polynomials for j = 1, 3, 5, 7. This can be
done by executing the following statements in the command window:
x = linspace(-1, 1, 201);
T1 = cos(acos(x));
T3 = cos(3*acos(x));
T5 = cos(5*acos(x));
T7 = cos(7*acos(x));
subplot(2,2,1), plot(x, T1)
subplot(2,2,2), plot(x, T3)
subplot(2,2,3), plot(x, T5)
subplot(2,2,4), plot(x, T7)
1 1
0.5 0.5
0 0
−0.5 −0.5
−1 −1
−1 −0.5 0 0.5 1 −1 −0.5 0 0.5 1
1 1
0.5 0.5
0 0
−0.5 −0.5
−1 −1
−1 −0.5 0 0.5 1 −1 −0.5 0 0.5 1
(b) When you use the plot command, Matlab chooses (usually appropriately) default values
for the axes. Here, it chooses precisely the domain and range of the Chebyshev polynomials.
These can be changed using the axis command, for example:
2 1
1 0.5
0 0
−1 −0.5
−2 −1
−1 −0.5 0 0.5 1 −2 −1 0 1 2
2 2
1.5
1
1
0.5 0
0
−1
−0.5
−1 −2
−2 −1 0 1 −2 −1 0 1 2
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
−1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8 1
subplot(1,1,1)
plot(x, T1, ’b’)
hold on
plot(x, T3, ’r’)
plot(x, T5, ’g’)
plot(x, T7, ’c’)
The resulting plot is shown in Fig. 1.3. (You should see the plot in color on your screen.)
Remarks on Matlab Figures. We have explained that hold can be used to overlay plots on
the same axes, and subplot can be used to generate several di↵erent plots in the same figure. In
some cases, it is preferable to generate several di↵erent plots in di↵erent figures, using the figure
command. To clear a figure, so that a new set of plots can be drawn in it, use the clf command.
Problem 1.3.6. Write Matlab code that evaluates and plots the functions:
In each case, your code should not contain loops but should use arrays directly.
Problem 1.3.8. Use Matlab to recreate the plot in Fig. 1.4. Hints: You will need the
commands hold, xlabel, ylabel, and legend. The ± symbol in the legend can be created
using \pm.
10
y = 0.25*x*sin(x)
y = ± 0.25*x
8
2
y−values
−2
−4
−6
−8
−10
0 5 10 15 20 25 30 35 40
x−values
Figure 1.4: Example of a plot that uses Matlab commands hold, xlabel, ylabel, and legend.
1.3. MATLAB AS A SCIENTIFIC COMPUTING ENVIRONMENT 13
Problem 1.3.9. Explain what happens when the following Matlab code is executed.
for k = 1:6
x = linspace(0, 4*pi, 2b(k+1)+1);
subplot(2,3,k), plot(x, sin(x))
axis([0, 4*pi, -1.5, 1.5])
end
• A function is a file containing Matlab commands that are executed when the function is
called. The first line of a function must have the form:
function [out1, out2,... ] = FunctionName(in1, in2, ...)
By default, any data or variables created within the function are private. You can specify any
number of inputs to the function, and if you want it to return results, then you can specify
any number of outputs. Functions can call other functions, so you can write sophisticated
programs as in any conventional programming language.
In each case, the program must be saved in a M–file; that is, a file with a .m extension. Any editor
may be used to create an M–file, but we recommend using Matlab’s built-in editor, which can
be opened in one of several ways. In addition to clicking on certain menu items, the editor can be
opened using the edit command. For example, if we enter
edit ChebyPlots.m
in the command window, then the editor will open the file ChebyPlots.m, and we can begin entering
and modifying Matlab commands.
It is important to consider carefully how the script and function M–files are to be named. As
mentioned above, they should all have names of the form:
FunctionName.m or ScriptName.m
The names should be descriptive, but it is also important to avoid using a name already taken be one
of Matlab’s many built-in functions. If we happen to use the same name as one of these built-in
functions, then Matlab has a way of choosing which function to use, but such a situation can be
very confusing. The command exist can be used to determine if a function (or variable) is already
defined by a specific name and the command which can be used to determine its path. Note, for a
function file the name of the function and the name of the M–file must be the same.
To illustrate how to write functions and scripts, we provide two examples.
Example 1.3.2. In this example we write a simple function, PlotCircle.m, that generates a plot
of a circle with radius r centered at the origin:
14 CHAPTER 1. GETTING STARTED WITH MATLAB
function PlotCircle(r)
%
% PlotCircle(r)
%
% This function plots a circle of radius r centered at the origin.
% If no input value for r is specified, the default value is chosen
% as r = 1. We check for too many inputs and for negative input
% and report errors in both cases.
%
if nargin < 2
if nargin == 0
r = 1;
elseif r <= 0
error(’The input value should be > 0.’)
end
theta = linspace(0, 2*pi, 200);
x = r*cos(theta);
y = r*sin(theta);
plot(x, y)
axis([-2*r,2*r,-2*r,2*r])
axis square
else
error(’Too many input values.’)
end
−1
−2
−3
−4
−4 −3 −2 −1 0 1 2 3 4
• error is a built-in Matlab command. When this command is executed, the computation
terminates, and the message between the single quotes is printed in the command window.
Example 1.3.3. Here, we illustrate how scripts can be used in combination with functions. Suppose
that the concentration of spores of pollen per square centimeter are measured over a 15 day period,
resulting in the following data:
day 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
pollen count 12 35 80 120 280 290 360 290 315 280 270 190 90 85 66
(a) First, we write a function that has as input a vector of data, and returns as output the mean
and standard deviation of this data.
Matlab has several built-in functions for statistical analysis. In particular, we can use mean
and std to compute the mean and standard deviation, respectively. Thus, the function we
write, named GetStats.m, is very simple:
%
% Script: PollenStats
%
% This script shows a statistical analysis of measured pollen
% counts on 15 consecutive days.
%
%
% p is a vector containing the pollen count for each day.
% d is a vector indicating the day (1 -- 15).
%
p = [12 35 80 120 280 290 360 290 315 280 270 190 90 85 66];
d = 1:length(p);
%
% Get statistical data, and produce a plot of the results.
%
[m, s] = GetStats(p);
bar(d, p, ’b’)
xlabel(’Day of Measurement’)
ylabel(’Pollen Count’)
hold on
plot([0, 16], [m, m], ’r’)
plot([0, 16], [m-s, m-s], ’r--’)
plot([0, 16], [m+s, m+s], ’r--’)
text(16, m, ’<-- m’)
text(16, m-s, ’<-- m - s’)
text(16, m+s, ’<-- m + s’)
hold off
(b) We now write a script, PollenStats.m, to generate and display a statistical analysis of the
pollen data.
Once the programs are written, we can run the script by simply entering its name in the
command window:
>> PollenStats
Problem 1.3.10. Write a function M–file, PlotCircles.m, that accepts as input a vector,
r, having positive entries, and plots circles of radius r(i) centered at the origin on the same
axes. If no input value for r is specified, the default is to plot a single circle with radius r =
1. Test your function with r = 1:5. Hint: Matlab commands that might be useful include
max, min and any.
1.3. MATLAB AS A SCIENTIFIC COMPUTING ENVIRONMENT 17
400
350
250
200
<−− m
150
100
<−− m−s
50
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Day of Measurement
Figure 1.6: Bar graph summarizing the statistical analysis of pollen counts from Example 1.3.3
• Change the location where the published document is saved on your computer.
18 CHAPTER 1. GETTING STARTED WITH MATLAB
%
% Script: Cheby_c
%
% This creates the figure for the plotting example. Here
% we illustrate the use of the hold command.
%
% Note that we make the line width a bit thicker and the
% font size a bit larger to make for better displays.
%
x = linspace(-1, 1, 201);
T1 = cos(acos(x));
T3 = cos(3*acos(x));
T5 = cos(5*acos(x));
T7 = cos(7*acos(x));
figure(1), clf
axes('FontSize', 18), hold on
plot(x, T1, 'b', 'LineWidth', 2)
plot(x, T3, 'r', 'LineWidth', 2)
plot(x, T5, 'g', 'LineWidth', 2)
plot(x, T7, 'c', 'LineWidth', 2)
hold off
1
1.3. MATLAB AS A SCIENTIFIC COMPUTING ENVIRONMENT 19
More extensive reports should be prepared using software such as LATEX. Plots created in Mat-
lab can be easily printed for inclusion in the report. Probably the easiest approach is to pull down
the File menu on the desired Matlab figure window, and let go on Print.
Another option is to save the plot to a file on your computer using the Save as option under the
File menu on the figure window. Matlab supports many types of file formats, including encapsu-
lated postscript (EPS) and portable document format (PDF), as well as many image compression
formats such as TIFF, JPEG and PNG. These files can also be created in the command window, or
in any M–file, using the print command. For detailed information on creating such files, open the
help browser to the associated reference page using the command doc print.
An example of a LATEX document that includes a figure can easily be generated using the Publish
tool by using Edit Publishing Options ... to change the file type to latex.
In addition to plots, it may be desirable to create tables of data for a report. Three useful
commands that can be use for this purpose are disp, sprintf and diary. When used in combination,
disp and sprintf can be used to write formatted output in the command window. The diary
command can then be used to save the results in a file. For example, the following Matlab code
computes a compound interest table, with annual compounding:
a = 35000; n = 5;
r = 1:1:10;
rd = r/100;
t = a*(1 + rd).^n;
diary InterestInfo.dat
disp(’ If a = 35,000 dollars is borrowed, to be paid in n = 5 years, then:’)
disp(’ ’)
disp(’ Interest rate, r Total paid after 5 years’)
disp(’ ==================================================’)
for i = 1:length(r)
disp(sprintf(’ %5.2f %8.2f ’, r(i), t(i)))
end
diary off
If the above code is put into a script or function M–file, then when the code is executed, it prints
the following table of data in the command window:
Here, the diary command is used to open a file named InterestInfo.dat, and any subsequent re-
sults displayed in the command window are automatically written in this file until it is closed with the
diary off command. Thus, after execution, the above table is stored in the file InterestInfo.dat.
20 CHAPTER 1. GETTING STARTED WITH MATLAB
An alternative approach is to use the fopen, fprintf and fclose commands as follows:
a = 35000; n = 5;
r = 1:1:10;
rd = r/100;
t = a*(1 + rd).^n;
fid = fopen(’InterestInfo.dat’, ’w’);
fprintf(fid, ’ If a = 35,000 dollars is borrowed, to be paid in n = 5 years, then:\n\n’);
fprintf(fid, ’ Interest rate, r Total paid after 5 years\n’);
fprintf(fid, ’ ==================================================\n’);
for i = 1:length(r)
fprintf(fid, ’ %5.2f %8.2f\n’, r(i), t(i));
end
fclose(fid);
In this bit of Matlab code,
• We use fopen to request that a file, called InterestInfo.dat, be opened for writing. Matlab
opens the file, and specifies it with a unique file indentifier, which we call fid.
• fprintf is then used to write data, text, etc., to the file. The commands \n indicate that the
next printing command should begin on a new line.
• fclose is then used to close the file, so it can no longer be modified.
A word of warning about writing to files: If we create a script M–file containing the above code using
the sprintf, disp, and diary, and we run that script several times, the file InterestInfo.dat will
collect the results from each run. In many cases the first set of runs may be used to debug the code,
or to get the formatted output to look good, and it is only the final set that we want to save. In this
case, it is recommended that you comment out the lines of code containing the diary commands
(that is, put the symbol % in front of the commands) until you are ready to make the final run.
On the other hand, if we create a script M–file containing the code with fopen, fprintf and
fclose, and we run that script several times, the file InterestInfo.dat will contain only the results
from the final run. This is because we used ’w’ for the file access type in the fopen command, which
tells Matlab to open the file for writing, and discard any existing contents. If we want to append
results to an existing file, without discarding its current contents, then we should replace ’w’ with
’a’ in the fopen command. See doc fopen for more information.
function f = Runge(x)
%
% f = Runge(x);
%
% This function evaluates Runge’s function, f(x) = 1/(1 + x^2).
%
% Input: x - vector of x values
%
% Output: f - vector of f(x) values.
%
f = 1 ./ (1 + x.*x);
1.3. MATLAB AS A SCIENTIFIC COMPUTING ENVIRONMENT 21
To evaluate this function at, say, x = 1.7, we can use the Matlab statement:
>> y = Runge(1.7)
Or, if we want to plot this function on the interval 5 x 5, we might use the Matlab statements
>> x = linspace(-5, 5, 101);
>> y = Runge(x);
>> plot(x, y)
Although this approach works well, it is rather tedious to write a function M–file whose definition
is just one line of code. An alternative approach is to use an anonymous function:
>> Runge = @(x) 1 ./ (1 + x.*x);
Here the notation @(x) explicitly states that Runge is a function of x, and the symbol @ is referred
to as a function handle.
Once Runge has been defined, we can evaluate it at, say, x = 1.7, using the Matlab statement:
>> y = Runge(1.7);
Or, to plot the function on the interval 5 x 5, we might use the Matlab statements above.
Note that it is always best to use array operators (such as ./ and .*) when possible, so that
functions can be evaluated at arrays of x-values. For example, if we did not use array operations in
the above code, that is, if we had used the statement Runge = @(x) 1 / (1 + x*x), (or the same
definition for f in the function Runge) then we could compute the single value Runge(1.7), but y
= Runge(x) would produce an error if x was a vector, such as that defined by x = linspace(-5,
5, 101).
Anonymous functions provide a powerful and easy to use construct for defining mathematical
functions. In general, if f (x) can be defined with a single line of code, we use an anonymous function
to define it, otherwise we use a function M–file.
Problem 1.3.11. The Matlab functions tic and toc can be used to find the (wall clock)
time it takes to run a piece of code. For example, consider the following Matlab statements:
f = @(x) 1 ./ (1 + x.*x);
tic
for i = 1:n
x = rand(n,1);
y = f(x);
end
toc
When tic is executed, the timer is started, and when toc is executed, the timer is stopped,
and the time required to run the piece of code between the two statements is displayed
in the Matlab command window. Write a script M–file containing these statements.
Replace the definition of f (x) by a function M–file. Run the two codes for each of
n = 100, 200, 300, 400, 500. What do you observe? Repeat this experiment. Do you ob-
serve any di↵erences in the timings?
Problem 1.3.12. Repeat the experiment in Problem 1.3.11, but this time use
ex + sin ⇡x
f (x) = .
x2 + 7x + 4
Problem 1.3.13. Write MATLAB code that will create the plot shown in the following
Figure 1.8. Your code should be in either a MATLAB script or function m-file. You can
use the code given in Example 1.3.2 as a template.
22 CHAPTER 1. GETTING STARTED WITH MATLAB
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1 -0.5 0 0.5 1
Problem 1.3.14. To plot a surface, you can use a combination of the MATLAB functions:
• linspace and meshgrid to generate a set of (x, y) coordinates, and
• mesh or contour to plot the surface.
Read the document pages on these functions, and use them to plot the surfaces of the fol-
lowing (use both mesh and contour):
x2 y 2
(a) f (x, y) = (x2 + 3y 2 )e , 3 x 3, 3y3
(b) g(x, y) = 3y/(x2 + y 2 + 1) , |x| 2, |y| 4
(c) h(x, y) = |x| + |y| , |x| 2, |y| 1