Documente Academic
Documente Profesional
Documente Cultură
January, 2015
Contents
Contents 1
1 Introduction 4
3 Basic Operations 8
3.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Some basic functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
5 Matlab Help 20
5.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
6 Path 22
6.1 Generating a Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
6.2 Other Matlab icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
10 Graphs 30
10.1 Graph display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
10.2 Saving Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
10.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
11 Programming in Matlab 35
11.1 The IF. . . ELSE. . . END construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
11.2 The SWITCH. . . CASE. . . END construction . . . . . . . . . . . . . . . . . . . . . . . . . . 37
11.3 The FOR. . . END construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
11.4 The WHILE. . . END construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
11.5 The BREAK construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
11.6 The CONTINUE construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
11.7 The TRY. . . CATCH. . . END construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
11.8 The RETURN construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
11.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
12 Random numbers 48
12.1 Generating random numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
12.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
13 Equations 52
13.1 Linear equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
13.2 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
13.3 The interpolating polynomial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
13.4 Integration and Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
13.5 Non-linear equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
13.5.1fzero function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
13.5.2fsolve function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
13.6 Solving One equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
13.7 Solving One equation with parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
13.8 Solving Two equations with parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3
14 Toolbox 62
14.1 Financial Time Series toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
14.2 Statistics toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
14.3 GARCH toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
14.3.1Example of Analysis and Estimation using the GARCH model. . . . . . . . . . . . 68
14.4 Optimization toolbox: Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
14.4.1Example of minimization without constraints . . . . . . . . . . . . . . . . . . . . . 71
14.4.2Example of minimization with constraints (inequalities) . . . . . . . . . . . . . . . 71
14.4.3Example of constrained minimization with bounds . . . . . . . . . . . . . . . . . . 72
14.4.4Example of constrained minimization with the gradient . . . . . . . . . . . . . . . 73
14.4.5Example of minimization with parameters . . . . . . . . . . . . . . . . . . . . . . . 73
14.5 Financial toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
14.5.1Put and call option pricing according to the Black-Scholes model . . . . . . . . . 74
14.5.2Black-Scholes Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
14.5.3Binomial Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
15 Exercises 75
16 References 83
4 2.1 Starting Matlab
1. Introduction
The purpose of this tutorial is to present the basics of MATLAB (“MATrix for LABoratory”). It is
aimed at people who have no prior knowledge of this package. You are encouraged to work at the
computer as you read these notes and experiment with the examples.
Matlab is a programming language and a numerical computing environment that uses vectors
and matrices as its basic data types. Among other things, Matlab allows easy matrix manipulation
and plotting of data and functions in two and three dimensions. It is a commercial product licensed
by The MathWorks, Inc, and has a basic code and various specialized libraries called “toolboxes”.
The scope and power of Matlab goes well beyond these notes. These notes are based on those
from Javier Gil (2006) and Garcı́a de Jalón et al. (2005) and on the book by Cesar Perez (2002). You
may wish to consult various books, tutorials and guides such as the MATLAB User”s Guide and
Reference Guide or those mentioned in the bibliography.
To start Matlab, just double click on the Matlab icon on your desktop or open it through the Start
Menu. We recommend you to go to “Desktop” and select Default. Once Matlab has been opened,
the desktop appears, containing tools (graphical user interfaces) for managing files, variables, and
applications associated with Matlab. Figure 1 shows the default desktop. This configuration can
easily be changed by the user in the View menu.
The desktop is Matlab’s general Workspace. We will explain here the most important elements
from this screen:
• Command Window. This is the most important one. Commands are typed here at the Matlabs
prompt (>>).
2.2 Writing in Matlab 5
• Current Directory. This shows the Matlab files in the current folder and carries out operations
on files such as opening them and searching for contents.
• Workspace. This holds information about all variables defined in the current session. It allows
you to see and change the arrays with which you are working.
• Command history. This shows the complete history of functions entered in the Command
Window and allows them to be copied and run.
The easiest way to assess the power of Matlab is to write on the Command Window. This is the
main way of communicating with Matlab. Type your commands at the prompt (>>) and, then,
press Enter. However, it is not so straightforward: There are some rules for writing in Matlab. The
following are the ones we consider are important and, therefore, to be remembered:
1. You can create variables in the Command window and Matlab stores information in these
variables in the Matlab Workspace. For example1 :
>> price=20
price =
20
>> quantity=5000
quantity =
5000
You can check that Matlab stores these variables in the Matlab Workspace.
2. Matlab is case sensitive. Names must not contain spaces and must start with a letter but a
blank space can be left before or after the minus sign, tow dots and brackets. A maximum of 31
characters is allowed.
3. Some words are reserved for programming: for, end, if, while, else, elseif, case,
break. Other words have a specific meaning unless changed by the user: ans, pi, eps, inf,
NaN, i, j, nargin, nargout2 . For example:
>> i
ans =
0 + 1.0000i
4. Comments are entered by starting the line with the % character (You can comment on a
paragraph using the command %{, %}); Matlab ignores everything after this on that line:
%we will compute the value of apples
5. The disp command displays the array named after it:
>> disp 25.000
25.000
>> disp(‘Welcome to this Master’)
Welcome to this Master
6. All entries are run sequentially as they are positioned in the line. They can be separated
by commas or semicolons. If commas are used, the output is shown in the Command Window.
1 If you do not specify the name of the answer, Matlab chooses ans.
2 These will be described in greater detail in the following chapters.
6 2.2 Writing in Matlab
If semicolons are used, the output is suppressed. However, the output is always stored in the
Workspace. This is crucial in programming and data analysis:
>> price=50, quantity=2, value=price*quantity
price =
50
quantity =
2
value =
100
>> price=50, quantity=2, value=price*quantity;
price =
50
quantity =
2
>> price=50; quantity=2; value=price*quantity;
7. Long entries occupying more than one line can be continued on the next line, by adding three
dots at the end of the first line:
>> Var=1/2+4/7-2/3+5-4.5+
Error: Expected a variable, function, or constant, found
"end of line".
>> Var=1/2+4/7-2/3+5-4.5+...
1/32+43/7+56
Var =
63.0789
8. The command who shows the workspace and the command whos shows all details of what is
in the workspace:
>> who
Your variables are:
Var quantity
price value
>> whos
Name Size Bytes Class
Var 1x1 8 double array
price 1x1 8 double array
quantity 1x1 8 double array
value 1x1 8 double array
Grand total is 4 elements using 32 bytes
9. The clear command will delete variables and functions from memory. clear all removes
all variables from the workspace. clc clears the command window and homes the cursor.
2.2 Writing in Matlab 7
10. The following is a list of the main keys and combinations that can be used in the Command
Window:
11. All Matlab computations are double precision. However, it is possible to specify numeric
values at the Command Window. This affects only the way numbers are displayed but not the way
the calculations are carried out. It is often useful to ask Matlab to show numbers in a long format.
The command format can be used to switch between different output display formats:
>> format short % Scaled fixed point format with 5 digits.
Same as default.
>> pi
ans =
3.1416
>> format long % Scaled fixed point format with 15 digits.
>> pi
ans =
3.14159265358979
>> format long e % Floating point format with 15 digits.
It will include the exponent.
>> pi
ans =
3.141592653589793e+000
>> format short e % Floating point format with 5 digits.
It will include the exponent.
>> pi
ans =
3.1416e+000
>> format hex % Hexadecimal format.
>> pi
ans =
400921fb54442d18
If followed by g instead of e, eliminates the exponent.
8 3.1 Variables
12. Addition is not exactly commutative with double precision arithmetic and can be problematic
when comparing values. One simple solution is to ask whether the difference between two numbers
is zero, whether it is smaller than eps (floating point for relative accuracy that is 2.2204e − 016 on
most machines) or some other pre-specified number.
>> 0.42-0.5+0.08
ans =
-1.38777878078145e-017
>> 0.42+0.08-0.5
ans =
0
>> eps
ans =
2.22044604925031e-016
3. Basic Operations
3.1 Variables
Matlab does not have a special command to create variables; it simply creates a variable with a
direct assignment of its value:
>> q=500
q =
500
The value of variable q will be 500 until it is changed with a new assignment:
>> q=q+800
q =
1300
3.2 Numbers
Matlab is an interactive program that allows you to carry out a great variety of mathematical op-
erations easily and simply. You can work in Matlab with various types of numbers and numerical
expressions such as integers, rational numbers, real numbers and complex numbers. These num-
bers can then be used as the arguments to functions. There is an important group of irrational
and real numbers that need special treatment because of their frequent use. Matlab can handle the
following (Table 2):
Arithmetic operations in Matlab are defined according to standard mathematical conventions
(Table 3):
For example:
>> 5*2ˆ4+(3-1)/7
ans =
80.2857
3.3 Some basic functions 9
Matlab has a very complete range of predefined functions. In addition to basic mathematical oper-
ations, Matlab includes common functions such as log or sin. If you type help elfun or help
specfun in the Command Window, Matlab will display a list of pre-programmed elementary and
specialized functions (which means that you can program your own functions, as described below).
>> help elfun
Elementary math functions.
Trigonometric.
sin - Sine.
sinh - Hyperbolic sine.
asin - Inverse sine.
asinh - Inverse hyperbolic sine.
cos - Cosine.
.
.
.
Exponential.
exp - Exponential.
log - Natural logarithm.
log10 - Common (base 10) logarithm.
log2 - Base 2 logarithm and dissect floating point number.
pow2 - Base 2 power and scale floating point number.
.
.
.
Complex.
abs - Absolute value.
.
.
.
Rounding and remainder.
fix - Round towards zero.
floor - Round towards minus infinity.
ceil - Round towards plus infinity.
10 3.4 Exercises
3.4 Exercises
Exercise 2 Evaluate the following MATLAB expressions by hand. Use MATLAB to check the answers
1. 2/2 ∗ 3
2. 6 − 2/5 + 72 − 1
3. 10/2/5 − 3 + 2 ∗ 4
4. 32 /4
5. (32 )2
6. 2 + round(6/9 + 3 ∗ 2)/2 − 3
7. 2 + f loor(6/9 + 3 ∗ 2)/2 − 3
8. 2 + ceil(6/9 + 3 ∗ 2)/2 − 3
This section shows how to create and transform vectors and matrices in Matlab.
4.1 Vectors
To create a vector of n elements in Matlab, each element of the vector must be separated by commas
or a blank3 :
V = [v1 , v2 , v3 , . . . , vn ] or V = [v1 v2 v3 . . . vn ]
or one can define a vector without placing all its elements between brackets. An element can be
selected from a vector or an element sub-set with a simple command. Table 4 shows how vectors
can be created and how an element can be selected from a vector or sub-set of elements.
3 Blank spaces must be avoided when listing a number in exponential form (2.2204e − 016).
4.1 Vectors 11
Example 1.
Create a vector with the element 1, 2, 5, 4.5, 2/3 and 23 called “v” and calculate its square
root and its transpose. Finally, choose the even elements of the squared vector and call it
“even”.
Matlab returns
>> v=[1,2,5,4.5,2/3,2 ˆ3]
v =
1.0000 2.0000 5.0000 4.5000 0.6667 8.0000
>> a=sqrt(v)
a =
1.0000 1.4142 2.2361 2.1213 0.8165 2.8284
>> vv=v’
vv =
1
2
5
4.5
0.6667
8
>> even=a(2:2:6)
even =
1.4142 2.1213 2.8284
12 4.2 Creating arrays
Example 2.
Create a vector “b” with initial value 10 and end value 45. Each element is spaced by 6
units. Do the same using linspace. Do you get the same results?
Matlab returns
>> b=[10:6:45]
b =
10 16 22 28 34 40
>> bb=linspace(10,45,6)
bb =
10 17 24 31 38 45
As already mentioned, Matlab is basically a program for matrix calculations. The following describes
how to define matrices and how to work with them in Matlab.
An array is just a rectangular arrangement of quantities in rows and columns. We have seen
that a vector is just an mx1 array. A matrix is an mxn array4 . It is easy to create a matrix in Matlab.
To create a matrix just separate rows with semicolons and put them between brackets. Remember
to separate elements in each row with a blank space or a comma. For example, a matrix 3x3 can
be introduced in the following two ways:
A = [a11 a12 a13 ; a21 a22 a23 ; a31 a32 a33 ] or
A = [a11 , a12 , a13 ; a21 , a22 , a23 ; a31 , a32 , a33 ].
An mxn dimension matrix can be defined similarly. The mathematical notation for a particular
element in an array is Aij which stands for “the value of the element at the intersection of row i and
column j in the array A”. In Matlab notation, the i − jth element of an array named A is denoted
A(i, j).
Matlab has various possibilities for defining a variable. Table 5 shows some of them.
4 We recommend that you name the vectors in lowercase and matrices in uppercase.
4.2 Creating arrays 13
Example 3.
Create a 2x10 matrix whose values equal 100. Next, change the even elements from the
first row for their square root.
Matlab returns
>> C(1:2,1:10)=100
C =
100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100
>> C(1,2:2:10)=sqrt(100)
C =
100 10 100 10 100 10 100 10 100 10
100 100 100 100 100 100 100 100 100 100
Example 4.
Create a matrix from other three matrices, the first is a 2x3 identity matrix, the second is
a 2x4 matrix of ones and the third is a 2x2 matrix of zeros. Ask Matlab for the size of the
new matrix.
Matlab returns
>> size(B)
ans =
2 9
14 4.3 Operating with arrays
Example 5.
Create a 3x4 matrix called M formed by the numbers 1 to 12, consecutively. Next,
• create a sub-matrix MM with the elements M11, M12, M31 and M32 .
Matlab returns
>> MM=M(1:2:end,1:2)
MM =
1 2
9 10
>> MMM=M(:,end)
MMM =
4
8
12
Once you know how to enter and display matrices, its easy to compute with them. Matlab can
operate with matrices using operators and functions. Table 6 shows the most important Matlab
matrix operators and functions.
Various examples are shown below. Practice with the operators and functions in Table 6. Matlab
has a large number of built-in functions, far more than the ones shown here. As you explore
Matlab’s capabilities, you may find its help documentation useful. Try typing help or helpwin at
the command prompt and explore the various types of functions available.
Example 6.
Multiply the two matrices A and B as matrices and element by element, where
A=[1 2; 3 4] and B=[5 6; 7 8]. What is the difference?
Matlab returns
19 22 5 12
43 50 21 32
Example 7.
Create a 3x3 A matrix and delete the first column. Then, change elements A(2 2) and
A(1 3) for their squares.
Matlab returns
1 2 3 2 3
4 5 6 5 6
7 8 9 8 9
>>A(2,2)=sqrt(A(2,2)); >>A(1,3)=sqrt(A(1,3));
16 4.4 Exercises
Example 8.
>> A*B
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> B*A
ans =
61 83
Careful: Note that the dot operator plays a specific role in Matlab. It is used for the
component wise application of the operator that follows the dot operator: A.*B or A./B
Example 9.
Create a 4x2 matrix A of normal random variables. Calculate the sum of the elements by
rows and the product by columns. Finally, calculate the maximum value of the columns
in A.
Matlab returns
4.4 Exercises
Exercise 3 Given a square random uniform matrix of order 3, obtain its inverse, its transpose and
its diagonal. Transform it into a lower triangular matrix, a higher triangular matrix and rotate it 90
degrees. Get the sum of the parts of the first row and the sum of the parts of the diagonal.
Exercise 4 Create a vector of the even whole numbers between 31 and 75.
1. 2, 4, 6, 8, . . .
4.4 Exercises 17
2. 10, 8, 6, 4, 2, 0, −2, −4
Exercise 6 Create a 3x10 matrix containing the first 10 multiples of 7 in row 1, the following 10 multi-
ples in row 2 and so on. Then replace even elements in the last row with zeros.
Exercise 8 Let x = [3 2 6 8]’ and y = [4 1 3 5]’ (NB. x and y should be column vectors).
4. Multiply each element in x by the corresponding element in y, calling the result ”z”.
5. Add up the elements in z and assign the result to a variable called ”w”.
Exercise 9 Given x = [3 1 5 7 9 2 6], explain what the following commands ‘mean’ by summarizing
the result of the command.
1. x(3)
2. x(1 : 7)
3. x(1 : end)
4. x(1 : end − 1)
5. x(6 : −2 : 1)
6. x([1 6 2 1 1])
7. sum(x)
xn = (−1)n+1 /(2n − 1)
Add up the elements of the version of this vector that has 100 elements.
1. ... compute the length of the hypotenuse of a right triangle given the lengths of the sides (try to
do this for a vector of side-length values).
2. ... compute the length of the third side of a triangle given the lengths of the other two sides, given
the cosine rule
c2 = a2 + b2 − 2(a)(b)cos(t)
Exercise 12 Given a vector, t, of length n, write down the MATLAB expressions that will correctly
compute the following:
1. ln(2 + t + t2 )
2. et (1 + cos(3t))
5. cot(t)
5. compute the standard error of the mean of each column of A (NB. the standard error of the mean
is defined as the standard deviation divided by the square root of the number of elements used
to compute the mean).
Exercise 14 Given the arrays x = [1 4 8], y = [2 1 5] and A = [3 1 6 ; 5 2 7], determine which of the
following statements will correctly execute and provide the result. If the command will not correctly
execute, state why it will not. Using the command whos may be helpful here.
1. x + y
2. x + A
3. x′ + y
4. A − [x′ y ′ ]
5. [x; y ′ ]
6. [x; y]
7. A − 3
4.4 Exercises 19
Exercise 15 Given the array A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5], explain the results of the following
commands:
1. A′
2. A(:, [1 4])
3. A([2 3], [3 1])
4. reshape(A, 2, 6)
5. A(:)
6. f lipud(A)
7. f liplr(A)
8. [A A(end, :)]
9. A(1 : 3, :)
10. [A; A(1 : 2, :)]
11. sum(A)
12. sum(A′ )
13. sum(A, 2)
14. [[A; sum(A)][sum(A, 2); sum(A(:))]]
Exercise 16 Given the array A from problem 15, above, provide the command that will
Exercise 18 1. Given that x = [1 5 2 8 9 0 1] and y = [5 2 2 6 0 0 2], execute and explain the results
of the following commands:
1. x > y
2. y < x
20 4.4 Exercises
3. x == y
4. x <= y
5. y >= x
6. x|y
7. x&y
8. x&(∼ y)
Exercise 19 The exercises here show the techniques of logical-indexing (indexing with 0-1 vectors).
Given x = 1 : 10 and y = [3 1 5 6 8 2 9 4 7 0], execute and interpret the results of the following
commands:
2. x(x > 5)
3. y(x <= 4)
6. x(y < 0)
5. Matlab Help
Matlab has a Help menu with options providing a large amount of information on the program.
The different options from the Help menu are:
1. Full Product Family Help: shows general information on Matlab and other products in the
family.
2. Matlab Help: See Figure 2. Contains general information on Matlab and its functions and
program concepts. Clicking on it opens a window with various chapters including the one
shown below:
Clicking on the Contents tab on the left of the screen opens a thematic index. The other tabs
are Index (word index), Search (search by terms) and Demos (examples).
4. Using the Command Window: Help window for the Command Window environment.
4.4 Exercises 21
7. Demos: Presents a collection of examples to help you to use Matlab (the same as Product
Demos).
Matlab help can also be found from the command line by typing:
>> help
and a screen will appear in the Command Window with an index of Matlab help themes. For
example, typing
>> help lang
will open a list with the expressions on the programming language.5
If you type
>> helpwin+“function name”
will open a help window with information on the function or command “function name”. For
example, typing
>> helpwin eye
will provide information on the identity matrix. This window also allows the functions source
code (View Code for) or a series of functions related with the identity matrix (See Also) to be con-
sulted, if available.
If you do not remember the exact name of a functions you want to learn more about, you can
use the command
>> lookfor +“incomplete name”
followed by the incomplete name of a function in the Command Window. For example, type
lookfor sv. What do you obtain?
5 Described in more detail in other sections.
22 5.1 Exercises
If you want to see a specified file, you can use the command
>> edit +“file name”
For example, edit sum.m opens the M-file sum.m in the default editor.
5.1 Exercises
6. Path
Matlab can work with a large number of functions which need not all be together in the same
folder. In fact, it is useful to keep functions created by users in folders other than those containing
the Matlab functions. So that it knows which functions to use, Matlab has what is called a Path.
The Matlab intrinsic functions are already included in the Path. However, the functions we
create are not, so that when we want to run them, it is necessary to say where they are saved so
that Matlab can locate them.
Suppose we have created a function6 called polyinterp.m and saved it in the files folder. To
run this function, it is necessary to tell Matlab where it is by aiming Matlab through the Current
Directory to our folder. (See Figure 3).
Once our address is in the Current Directory tab, its contents will appear and the polyinterp.m
function can be run.
Let us suppose that we want to work with a function that calls for other functions that are placed in
another folder. If we want to load all the functions from that folder, we will have to type the following
sentence in the Command Window:
addpath((genpath(’Folder address’)))
This will create a path that allows Matlab to work with the functions in this folder.
Another solution, more usually used to load toolboxes, would be to add these functions to Mat-
lab’s own Path 7 by going to
File > Set Path > Add Folder
where we must add our folder, giving its exact address and then move it to the end of the list
(Move to Bottom).
Matlab has two functions for reading and writing messages on screen:
• Function input
• Function disp
The input function prints a message on the command line and retrieves a numerical value (it
may also be the result of an expression). Once the message has been written, Matlab waits for the
user to enter the numerical value. The disp function displays the value of a matrix on the screen
without showing its name.
Example 10.
Enter the following expressions in the Command Window and see the outputs:
• n=input(’Type in the number of variables’)
Matlab returns
Note that if the ’s’ command is added in the input function, the value of age is stored by but
not evaluated. Note also that using disp returns only the value of the variable, not its name.
There are various ways to load data from other programs (for example Excel) into Matlab, of which
the most commonly-used ones are the following:
• Use Copy and Paste functions to copy the data and place them between brackets on a com-
mand line. This has various disadvantages since the data loaded in this way cannot be edited.
To avoid this, a *.m file can be created to allow the data to be edited.
• Use the load function that allows data to be loaded from a file with rows with equal length
separated by Intro (for example, a “*.txt” file).
For example, we will create a data file called “data.txt” with the Notepath, containing the
following lines:
23 45 67 23
12 89 74 52
and save it in the “MatlabCourse” folder. The command
data=load(’data.txt’)
will read these data and load them into the data variable.
• Other commands for loading data are textread, fopen and fread. See Matlab help for further
information.
9.1 Scripts 25
Similarly, data obtained with Matlab can be exported to other programs such as Excel or Word.
For small amounts of data, the diary or fopen, fwrite commands can be used. For greater amounts
of data, the save command is recommended with the -ascii option, which is the suitable one for
these programs. See the Matlab help for further information.
All variables used in the current Matlab session can be saved in the Workspace. Nevertheless,
when you exit Matlab directly, all variables are lost. We recommend you to save your current
Workspace by selecting Save Workspace as... from the File menu. Choose a name for your file,
e.g., filename.mat and next click save. Remember that the file you just created must be located in
Matlabs search path.
Another way of saving your Worspace is to type Save Filename in the Command Window:8
>> save(’C: Documents and Settings Desktop/ filename’)
Until now we have worked only with the Command Window. However, this is not the easiest way
to use Matlab. To program in Matlab, it is better to create files with the *.m extension, using any
text editor, although it is better to use the Matlab editor which is also a Debugger (that is, it allows
the program to be run step-by-step to find any errors in it).
There are two possibilities for creating files. One uses scripts and the other, functions. Scripts
are nothing more than a set of commands written in an orderly way that are run when the file name
is entered. In this case, the variables appear in the Workspace and the file has neither input nor
output data.
Functions allow the creation of new programs and are similar to those already within Matlab.
They have input and output parameters. These files start with:
function[output parameters]=function name(input parameters)
In both cases, files with the *.m extension can be called, even themselves, recursively.
9.1 Scripts
As mentioned, scripts are nothing more than a set of commands that are run in order. A script is
run simply by entering the file name without its extension in the command window. For example, if
the file has the filename “Myname.m” then the Matlab command Myname will execute the statement
in the file. Be aware that variables in a script file are global and will change the value of variables
of the same name in the environment of the current Matlab session.
We recommend you to put ; after each sentence in the file to prevent all the results from
appearing on the screen. To see the results of any of them, remove the ; from this command.
To see the results of a script while it is running, use the echo command. Some echo commands
are9 :
matlab.mat. When one later reenters Matlab, the command load will restore the Workspace to its former state.
9 Use the help facility to see all of them.
26 9.2 Functions
• echo file on, where “file” is the name of a function file, activates the echo command in this
function.
Example 11.
Build a script called “matrix1.m” and save it in the “MatlabCourse” folder in which, given
a value m = 5, it returns the following matrices:
m=5;
% 1) Identity matrix
m_ident=eye(m);
% 2) matrix of normal random variables
m_norm=randn(m);
% 3) Multiplication of matrices
m_mult=m_ident*m_norm;
9.2 Functions
10 The variables varargin and varargout also exist. See Matlab help for further information.
9.3 Debugger 27
Example 12.
Build a function “matrix2.m” and save it in the “MatlabCourse” folder with the input value
m giving the range of a square matrix. This function must calculate the following matrices
and return the product of the two.
function[m_mult]=matriz2(m)
% Identity matrix
m_ident=eye(m);
% matrix of normal r.v.
m_norm=randn(m);
%Multiplication of matrices
m_mult=m_ident*m_norm;
9.3 Debugger
With the Matlab editor, in addition to create and modify *.m files, we can also execute these files
step by step and check if errors exist (it is knows as to purify).
The Matlab editor shows, by default, different sentences in different colors. For example, it
shows comments in green. Moreover, it cares about quotation marks and brackets that open and
close. If one lays the cursor on a bracket, it indicates its equivalent and, in the cases when there is
not one, it appears crossed off. If we want to comment (uncomment) on various lines at the same
time, it is enough to mark them, click on the right button and choose “Comment” (“Uncomment”).
Another option that appears when one clicks on the right button is the “SmartIndent” that organizes
the indent of the selected loop.
To use the debugger, it is enough to indicate in which line of the program we want to stop its
execution. Therefore, we need to click in front of the line and a red point (“breakpoint”) will appear
that indicates Matlab where to stop. When the program is executed, it will stop at the “breakpoint”
line and a green arrow will appear that shows the sentence where the execution is detained (before
28 9.5 Exercises
executing it). If the cursor is positioned on a variable, a small window will appear indicating the
actual numerical value of the variable.
When the file is executed with the debugger, its buttons activate. These are:
• Set/Clear breakpoint: Positions or deletes a “breakpoint” in the same line of the cursor.
• Clear all breakpoints: Eliminates all the “breakpoints” from the file.
• Step: Proceeds one step in the execution without entering in the evoked users’ functions, if
there are any in the line.
• Step In: Proceeds one step in the execution entering in the evoked users’ functions, if there
are any in the line.
• Stack: A scroll-down list appears in the right side of the bar. It allows you to choose the
working space or the variables that you want to eliminate.
When a program is executed using the debugger, it is possible to type in the command window
an expression to be calculated and see its results. Matlab also allows you to introduce conditional
“breakpoints” (yellow points). In this case, the program only stops when a certain condition is
satisfied. If you want to introduce a condition, you just have to click with the right button on the
line where you want to position it and choose Set/Modify conditional breakpoint. Then, a window
will open and you have to write there the condition that must be satisfied for the program to stop
its execution.
9.5 Exercises
Exercise 21 Copy the following code in an empty document of the editor of Matlab and save it under
the name “HelloWorld.m” in the “MatlabCourse” folder.
function[b]=HelloWorld(a)
% HelloWorld displays nice messages
% format b=HelloWorld(a)
% a is a number
% if a>0 a happy message is displayed
% if a<0 a sad message is displayed
% b contains the displayed message
if a>0
b='HelloWorld';
else
b='Goodbye cruel world...';
end
disp(b)
Exercise 22 Copy the following code in an empty document of the editor of Matlab and save it under
the name “Myfigure.m” in the “MatlabCourse” folder.
9.5 Exercises 29
function Myfigure(imagefile,titletext,xtext,ytext)
%MyFigure illustrates how to create a nice figure
%which plots your data using a function
% Format: makemyfigure(imagefile,titletext,xtext,ytext)
% -imagefile is a .mat file containing an image (as X)
% (try with spine.mat or topo.mat)
% -titletext is a string for the plot title
% -xtext,ytext are strings for the x- and y- axes
% Created March 28, 2001 by Bill
%Myfigure('spine.mat','titulo','ejex','ejey')
%default values for subplot
rows=1;
cols=1;
index=1;
switch nargin
case 3
ytext='y-axis';
case 2
xtext='x-axis';
ytext='y-axis';
case 1
titletext='title';
xtext='x-axis';
ytext='y-axis';
case 0
imagefile='spine.mat';
titletext='title';
xtext='x-axis';
ytext='y-axis';
end
load(imagefile)
if exist('X')
data=X;
else
whos
q=input('Which variable is the image?: ','s');
if ˜isempty(q) & exist(q)
data=eval(q);
else
return;
end
end
figure
subplot(rows,cols,index)
30 10.1 Graph display
imagesc(data)
title(titletext)
xlabel(xtext)
ylabel(ytext)
10. Graphs
• plot() creates a graph from vectors or columns in a matrix, using the linear scale.
• plotyy() creates two graphs with linear scales of two functions with two scales, one right and
the other left.
Once the graph is displayed, the following commands can be used to alter its parameters:
• gtext(’text’) write text with the help of the mouse; just enter the command and click with
the mouse at the point at which the text is to appear in the graph.
• grid on; grid off switches the grid in the graph on or off.
If more than one lines is to be drawn in the same graph, each line should be given a different
style by changing either its color or its form. Table 7 shows the Matlab options.
When various lines are drawn, Matlab chooses a different color from the table by default. The
following example shows how Matlab acts and how it can be modified:
10.1 Graph display 31
Example 13.
>> x=0:pi/12:5*pi;
>> y=[sin(x);cos(x);3*sin(x);5*cos(x)]’;
>> plot(x,y)
>> plot(x,y(:,1),’*c’,x,y(:,2),’.y’,...
x,y(:,3),’--m’,x,y(:,4),’-.k’)
5 5
4 4
3 3
2 2
1 1
0 0
−1 −1
−2 −2
−3 −3
−4 −4
−5 −5
0 2 4 6 8 10 12 14 16 0 2 4 6 8 10 12 14 16
There are many commands to change the lines in a graph, their thickness, size of markers etc.
For more information, see the program’s help facility.
32 10.1 Graph display
Lines can be added to an existing graph using the hold on command to add and hold off to
stop adding with the syntax, for example:
>> plot(x,y(:,1))
>> hold on
>> plot(x,y(:,2),’r’)
Various sub-graphs can be shown in the same graph (Figure 6). The window is divided into m
horizontal and n vertical partitions so that to draw in partition i, use the subplot(m,n,i) com-
mand, with the syntax, for example:
1 1
0.5 0.5
0 0
−0.5 −0.5
−1 −1
0 5 10 15 0 5 10 15
3 5
0 0
−1
−2
−3 −5
0 5 10 15 0 5 10 15
Figure 6: Sub-graphs
A title, axes, color changes, etc, can be added to each sub-graph using the commands described
above.
By default, Matlab adjusts the scale of axes to match the minimum and maximum of the line to
be drawn. The axis command allows the minimum and maximum values of the axes to be changed.
axis[xmin, xmax, ymin, ymax]
Unless told otherwise, Matlab creates graph windows sequentially, giving each a consecutive
number. The command figure(n) activates graph number n and allows the graph to be created
with this number.
To close a specific graph, use the command close(n).
To clean an active figure, use the command clf, which deletes the graph in the figure and leaves
it open but empty.
The command figure(gcf) makes the graph visible from the command window.
10.1 Graph display 33
Example 14.
Create a figure with the name 101 with the following syntax:
figure(101)
x=-2*pi:pi/36:2*pi;
plot(x,sin(x),'r',x,cos(x),'b')
title('Sine in red and cosine in blue')
figure(gcf)
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
−8 −6 −4 −2 0 2 4 6 8
There are other commands for drawing histograms, hist(), histfit(), bar charts, bar(), and
pie charts, pie(), as well as three-dimensional graphs, plot3(). These are all explained in the
Matlab help facility.
Finally, note that all these controls also appear in the graphical window, allowing the figure to
be altered once built.(See Figure 8).
• From the Figure menu, choose Save and save it in the desired directory.
• Choose Export in the Figure menu and save it with the required extension.
• Choose Print from the Figure menu and use the Page position and Page Setup commands
to orient the figure on the printed page.
An interesting alternative to these commands is the print command from the Command Window
used by entering:
where figure handle is the number of the figure to be printed and the Matlab forms and options
are11 :
10.3 Exercises
2
Exercise 23 Plot the functions x, x3 , ex and ex over the interval 0 < x < 4 . . .
1. on rectangular paper
3. on log-log paper
f (x) = sin(1/x)
for 0.01 < x < 0.1. How did you create x so that the plot looked good?
11 See the help facility for greater detail.
11.1 The IF. . . ELSE. . . END construction 35
Exercise 25 Plot the expression (determined in modeling the growth of the US population)
where t is the date, in years AD, using t = 1790 to 2000. What population is predicted in the year
2020?
Exercise 26 In polar coordinates (r, t), the equation of an ellipse with one of its focal point at the
origin is
where a is the size of the semi-major axis (along the x-axis) and e is the eccentricity. Plot ellipses
using this formula, ensuring that the curves are smooth by selecting an appropriate number of points
in the angular (t) coordinate. Use the command axis equal to set the proper axis ratio to see the
ellipses.
Although it does not have as many possibilities as other languages (Java, Fortran, C++,. . . ),
Matlab does allow easy programming and has various statements to form branches and loops. Use
the help lang facility for further information.
A branch is the carrying out of one or more operations depending on whether a condition is met
or not. A loop is the repetition of one or more operations on different data. Matlab has the following
programming statements:
• IF...ELSE...END
• SWITCH...CASE...END
• FOR...END
• WHILE...END
• BREAK
• CONTINUE
• TRY...CATCH...END
• RETURN
The conditions for the statements use the relational and logical operators shown in Table 8.
The following describes these statements in greater detail.
Put simply, this statement means: if the condition is met, carry out the operation. Then, we should
write the following:
if condition
operation
36 11.1 The IF. . . ELSE. . . END construction
end
If alternatives are required: if one condition is met, carry out operation 1, otherwise carry out
operation 2. In this case, we should write the following:
if condition
operation 1
else
operation 2
end
In its more complex form, the statement is written as:
if condition 1
operation 1
elseif condition 2
operation 2
elseif condition 3
operation 3
else option when the other 3 are not met
operation 4
end
These statements carry out operation 1 if condition 1 is met and so on. If no condition is met,
operation 4 is carried out (this last part is optional and may be omitted).
The if condition can be used to evaluate matrix conditions, in which case care must be taken
with what is being compared. If A and B are two matrices with equal ranges, then:
• if A==B means that all the elements in A are equal to those in B, two by two. If there is a
single different element, the statement is false.
• if A∼=B means that all the elements in A are different to those in B, two by two. If there is a
single equal element, the statement is false.
For these situations, the isequal(A,B) function is useful; this returns 1 if the matrices are
identical and 0 if there is any difference between them.
Here is an example of how this statement operates:
11.2 The SWITCH. . . CASE. . . END construction 37
Example 15.
function[w]=if_ejemplo(z)
if z<5
w=2*z;
elseif z<10
w=9-z;
elseif z<100
w=sqrt(z);
else
w=z;
end
Discuss what the program does and find the following values:
1. z = -2 w = ?
2. z = 1 w = ?
3. z = 9 w = ?
4. z = 60 w = ?
5. z = 200 w = ?
Example 16.
What does the following program do when the variable a takes the values a =
12,2,1,8,10?
switch a
case 0
disp('a=0')
case {1,2,3,4}
disp('a is less than 5')
case 10
disp('a is 10')
otherwise
disp('a is out of range')
end
This statement allows an operation to be repeated a specified number of times. It means that for
the defined values (in this case i = 1 : n), the following defined operation is carried out:
for i=1:n
operation
end
The loop carries out the operation for the values of i from 1 to n. Instead of i=1:n we can put
any sequence we wish. Generally, the expression is i =start value:increment:final value (if
increment = 1, it is omitted).
Any statement may be nested within another but take care to ensure that the counter variables
are different.
for i=1:n
for j=1:n
operation
end
end
If we write:
for i=A
operation
end
where A is a matrix, then the counter i takes the value of the relevant column in A in each
iteration.
The following are some examples of this statement:
11.4 The WHILE. . . END construction 39
Example 17.
Use the for statement to build a vector with the first 5 even numbers (0 . . . 8). The algo-
rithm should be:
4. Place the even number value in the position in the vector b matching that of the
counter.
b=zeros(5,1);
for i=1:5
even_number=2*i-2;
b(i)=even_number;
end
This statement carries out the operation if the condition meets a certain value.
while condition
operation
end
Here is an example:
Example 18.
What operation does the following statement do? What value will it return? What if c is
equal to 11? What if it is 1?
c=10;
while c>2
c=c/2;
end
This sentence allows a for or while loop to be terminated before it finishes. The break construction
terminates the loop statement and transfers execution to the statement immediately following the
loop.
40 11.6 The CONTINUE construction
Example 19.
a=10;
while a>2
a=a/2;
if a<5
break;
end
end
The loop will terminate when a < 5 and the result will be different. What will be the
solution now?
The continue statement is used for passing control to next iteration of for or while loop. This
statement causes an immediate jump to the operation following a for or while loop, leaving all the
statements between continue and the end of the loop unevaluated.
The continue statement works somewhat like the break statement. Instead of forcing termi-
nation, however, ’continue’ forces the next iteration of the loop to take place, skipping any code in
between.
Example 20.
a = 10;
%while loop execution
while a < 20
if a == 15
% skip the iteration
a = a + 1;
continue;
end
fprintf('value of a: %d\n', a);
a = a + 1;
end
operation 2
end
If an error occurs in operation 1, execution will pass to operation 2. If no error occurs, the
second operation will never be carried out.
Example 21.
A=rand(5);
B=ones(3);
try
C = [A; B]
catch
disp('Error, matrix dimensions do not match')
end
This operation causes a return from the function, immediately terminating the program.
Example 22.
The following statement allows a return to the command window if the matrix is empty,
without calculating its determinant.
A=[];
if isempty(A)
d=1;
return
else
d=det(A);
end
11.9 Exercises
Exercise 27 Build an algorithm to calculate how to remove the mean of a series with data a=[2 3 5 8
10]. The algorithm must include the following steps:
Check that the result is the same as using the functions of Matlab:
42 11.9 Exercises
b=sum(a)/length(a);
a=a-b;
a=a-mean(a);
a=detrend(a,0);
a=0:2:10;
for z=1:length(a)
if a(z)>=5
disp('big')
else
disp('little')
end
end
switch a
case 0
disp('a=0')
case{1,2,3,4}
disp('a is less than 5')
case 10
disp('a is 10')
otherwise
disp('a is out of range')
end
Exercise 29 Create the vector x = randperm(35) and then evaluate the following function using only
logical indexing:
2 if x≤6
y(x) = x−4 if 6 ≤ x < 20
36 − x if 20 ≤ x ≤ 35
You can check your answer by plotting y vs. x with symbols. The curve should be a triangular
shape, always above zero and with a maximum of 16. It might also be useful to try setting x to 1 : 35.
Using multiple steps (or a simple Mfile) is recommended for this problem.
Exercise 30 In each of the following questions, evaluate the given MATLAB code fragments for each
of the indicated cases. Use MATLAB to check your answers.
1. if n>1 n=7 m=
m=n+1; n=0 m=
else n = −10 m=
M=n-1;
end
11.9 Exercises 43
2. if z<5
w=2*z;
elseif z>10 z=1 w =
w=9-z; z=9 w =
elseif z>100 z = 60 w =
w=sqrt(z); z = 200 w =
else
w=z;
end
3. if T<30
h=2*T+1; T = 50 h=
elseif T<10 T = 15 h=
h=t-2; T =0 h=
else
h=0;
end
4. if (0<x)&& (x<10)
y=4*x; x = −1 y =
elseif (10<x) && (x<40) x=5 y =
y=10*x; x = 30 y =
else x = 100 y =
y=500;
end
Exercise 31 Write brief scripts to evaluate the following functions. If you start each script with a
request for input (using input), you’ll be able to test that your code provides the correct results.
1.
T −2 if 0 < T < 100
h(T ) =
0.45T + 900 if T > 100
Test cases:
T =5 h = −5
T = 110 h = 949, 5
2.
−1 if x<0
f (x) = 0 if x=0
1 if x>0
3.
200 if y < 10000
200 + 0.1(y − 10000) if 10000 ≤ y > 20000
t(y) =
1200 + 0.15(y − 20000) if 20000 ≤ y > 50000
5700 + 0.25(y − 50000) if y ≥ 50000
44 11.9 Exercises
Test cases:
y = 5000 t = 200
y = 17000 t = 900
y = 25000 t = 1950
y = 75000 t = 11950
Exercise 32 Explain why the following if-block would not be a correct solution to the previous exer-
cise.
if y<1000
t=200
elseif 1000<y<2000
t=200+0.1*(y-10000)
elseif 20000<y<50000
t=1200+0.15*(y-20000)
elseif y<50000
t=5700+0.25*(y-5000)
end
Exercise 33 Given the vector x = [1 8 3 9 0 1], create a short set of commands that will
Exercise 34 Create an M-by-N array of random numbers (use rand). Move through the array, element
by element, and set any value that is less than 0.2 to 0 and any value that is greater than (or equal to)
0.2 to 1.
1. aij = xi yj
2. bij = xi /yj
3. ci = xi yi , then add up the elements of c.
4. dij = xi /(2 + xi + yj )
5. eij = reciprocal of the lesser of xi and yj
Exercise 36 Write a script that will use the random-number generator rand to determine the follow-
ing:
It will be worthwhile to run your script several times because you are dealing with random num-
bers. Can you predict any of the results that are described above?
11.9 Exercises 45
Exercise 37 Write a script that asks for a temperature (in degrees Fahrenheit) and computes the
equivalent temperature in degrees Celsius. The script should keep running until no number is provided
to convert. [NB. the function isempty will be useful here.]
∞
π2 − 8 X 1
= 2 (2n + 1)2
16 n=1
(2n − 1)
How many terms are needed to obtain an accuracy of 1e−12 ? How accurate is the sum of 100 terms
of this series?
Exercise 39 The present value of an annuity (a yearly sum of money) may be computed from the
formula
where A is the annuity (in $/year), i is the nominal yearly interest rate (in decimal form), n is the
number of years over which the annuity is paid and P is the present value ($).
Example computation: If i = 0.15 (15%), A = $100/year and n = 10 years then P = $501.88.
If you won the $1,000,000 State Lottery and the Lottery offered you the choice of $500,000 today
or $50,000/year for 20 years, which would you take? You can assume an inflation (interest) rate of
5%.
Exercise 40 The Fibonacci numbers are computed according to the following relation:
Fn = Fn−1 + Fn−2
with F 0 = F 1 = 1.
Fn /Fn−1
p
It is claimed that this ratio approaches the value of the golden mean ((1 + (5))/2). What do your
results show?
Exercise 41 The Legendre polynomials (Pn (x)) are defined by the following recurrence relation
with P0 (x) = 1, P1 (x) = x and P2 (x) = (3x2 − 1)/2. Compute the next three Legendre polynomials
and plot all 6 over the interval [-1,1].
p
1. Set a = 1, b = 1/ (2), t = 1/4 and x = 1
46 11.9 Exercises
Roman Decimal
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
2. Repeat the following commands until the difference between a and b is within some desired
accuracy:
y=a
a = (a + b)/2
b = sqrt(b*y)
t = t - x*(y - a)ˆ2
x = 2*x
How many repeats are needed to estimate pi to an accuracy of 1e−8 ? 1e−12 ? Compare the perfor-
mance of this algorithm to the result from Exercise 38, above.
*http://www.netcom.com/˜hjsmith/Pi/Gauss L.html
Exercise 43 Write a script that asks for an integer (n) and then computes the following based on the
value of the integer:
While the value of n is greater than 1, replace the integer with half of its value (n/2) if the integer
is even. Otherwise, replace the integer with three times its value, plus 1 (3 ∗ n + 1).
Make provision to count the number of values in (or the length of) the sequence that results.
Example calculation: If n = 10, the sequence of integers is 5, 16, 8, 4, 2, 1 and so the length is 6.
Make a plot of the length of the sequence that occurs as a function of the integers from 2 to 30.
For example, when n = 10, the length is 6 while for n = 15, the length is 17. Is there any pattern?
Try larger numbers to see if any pattern occurs. Is there any integer for which the sequence does not
terminate?
Exercise 44 Write a script/function that converts a Roman numeral to its decimal equivalent. There
are two distinct situations that you might design your program for:
1. The “old” style where the order of the symbols does not matter. In this case, IX and XI both mean
10 + 1 or 11. You should be able to handle the following conversion table:
2. The “new” style where the order of the symbols does matter. For example, IX is 9 (10 - 1), XC
is 90 (100 - 10). The conversion table given above still holds and you may assume for this case
that the only instances of ”order” you will encounter are
IV(4), IX(9), XL(40), XC(90), CD(400) and CM(900)
11.9 Exercises 47
Exercise 45 Write a function that will do the inverse of the previous problem - convert a decimal
number into a Roman number.
Exercise 46 The properties of saturated steam are tabulated in many books but that is not a useful
form for computer use. The following expressions were provided by Williamson (Chemical Engineering,
May 15, 1972, p. 128):
2
V liq = 0.01655 + (0.150326e−4 )Psat − (0.40488e−7 )Psat +
3 4
(0.665584e−10 )Psat − (0.4053e−13 )Psat
2 3
Hvap = 1142.342 + (0.76833)Psat − (0.004194)Psat + (0.11642e−4 )Psat −
4 5
(0.157e − 7)Psat + (0.8086e−11 )Psat
In all cases, the pressure is in psia and the equations are valid for pressures between 20 and 600
psia. Maximum error in any computation is below 1%.
1. Create a function that provides these steam properties for a given vector of pressures. To save
typing, you should be able to copy directly from the browser window and paste into the MATLAB
editor. Some further editing will be required, though.
2. Write a script that allows a user to get different steam properties as desired. The script should
run until the user decides to quit.
3. Extend your script to allow the user to specify the units set (e.g., SI, English, CGS) before request-
ing numerical values for the properties.
4. Extend the function from a. to provide the heat of vaporization of water as a property.
5. What if the user wants to specify the temperature rather than the pressure?
48 12.1 Generating random numbers
Exercise 47 11. Write a function which computes the cumulative product of the elements in a vector.
The cumulative product of the jt h element of the vector x, xj , is defined by
1. One that uses two for-loops to explicitly carry out the calculations, element by element. An ”inner”
loop should accumulate the product and an ”outer” loop should more through the elements of the
vector p.
2. One that uses the built-in function prod to replace the inner loop.
In each case, you can check your results with the built-in function, cumprod.
Exercise 48 Follow the directions for Exercise 47 but create a function that computes the cumulative
sum of the elements of a vector. The elements of the cumulative sum vector are defined by
sj = x1 + x2 + ... + xj
Random numbers are very useful in simulations. There are several built-in functions in MATLAB
that generate random numbers, such as rand(). Random number generators are not truly random.
Basically, the way it works is that the process starts with one number, which is called the seed.
Based on this seed, a process determines the next random number. Using that number as the
seed the next time, another random number is generated, and so forth. These are actually called
pseudo-random.
The function rand generate uniformly distributed random real numbers in the open interval
(0,1).
The seed for the rand function will always be the same each time MATLAB is started, unless the
initial seed is changed. The rng function sets the initial seed. There are several ways in which it
can be called:
>> rng(’shuffle’)
%uses the current date and time. The seed will always be different
>> rng(intseed)
%an integer can also be passed to be the seed
>> rng(’default’)
%default value used when MATLAB starts up
The rng function can also be called with no arguments, which will return the current state of
the random number generator:
12.2 Exercises 49
As rand returns a real number in the open interval (0, 1), multiplying the result by an integer
N would return a random real number in the open interval (0, N). For example, multiplying by 10
returns a real number in the open interval (0, 10), so the expression rand*10 would return a result
in the open interval (0, 10). The functionrandn is used to generate normally distributed random
real numbers.
As the rand function returns a real number, this can be rounded to produce a random integer.
For example,
>> round(rand*10)
would generate one random integer in the range from 0 to 10 inclusive (rand*10 would generate a
random real number in the open interval (0, 10); rounding that will return an integer). However,
these integers would not be evenly distributed in the range. A better method is to use the function
randi, which, in its simplest form, randi(imax), returns a random integer in the range from 1 to
imax, inclusive. For example, randi(4) returns a random integer in the range from 1 to 4. A range
can also be passed; for example, randi([imin, imax]) returns a random integer in the inclusive
range from imin to imax:
12.2 Exercises
1. Compute the mean of each column and assign the results to the elements of a vector called avg.
2. Compute the standard deviation of each column and assign the results to the elements of a vector
called s.
3. Compute the vector of t-scores that test the hypothesis that the mean of each column is no differ-
ent from zero.
4. If P r(|t| > 2.132) = 0.1 with 4 degrees of freedom, are any of the mean values in the vector avg
statistically different from 0?
Exercise 50 Compute and plot the path(s) of a set of random walkers which are confined by a pair
of barriers at +B units and -B units from the origin (where the walkers all start from).
A random walk is computed by repeatedly performing the calculation
50 12.2 Exercises
xj+1 = xj + s
where s is a number drawn from the standard normal distribution (randn in MATLAB). For example,
a walk of N steps would be handled by the code fragment
x(1) = 0;
for j = 1:N
x(j+1) = x(j) + randn(1,1);
end
There are three possible ways that the walls can ”act”:
1. Reflecting - In this case, when the new position is outside the walls, the walker is ”bounced”
back by the amount that it exceeded the barrier. That is,
when xj+1 > B, xj+1 = B − |B − xj+1 |
when xj+1 < (−B), xj+1 = (−B) + |(−B) − xj+1 |
If you plot the paths, you should not see any positions that are beyond —B— units from the
origin.
2. Absorbing - In this case, if a walker hits or exceeds the wall positions, it ”dies” or is absorbed
and the walk ends. For this case, it is of interest to determine the mean lifetime of a walker (i.e.,
the mean and distribution of the number of steps the ”average” walker will take before being
absorbed).
3. Partially absorbing - This case is a combination of the previous two cases. When a walker
encounters a wall, ”a coin is flipped” to see if the walker reflects or is absorbed. Assuming a
probability p (0 < p < 1) for reflection, the pseudo-code fragment that follows uses the MATLAB
uniform random-number generator to make the reflect/absorb decision:
if rand < p
reflect
else
absorb
end
What do you do with all the walks that you generate? Compute statistics, of course. Answering
questions like:
• What is the standard deviation of the position of the walkers as a function of time?
• For the absorbing/partial-reflection case, a plot of the number of surviving walkers as a function
of step numbers is a very interesting thing.
Exercise 51 Create a function that generates random arrays of integers between a and b, inclusive.
Use the definition line
12.2 Exercises 51
function A = randint(a,b,M,N)
where a and b define the (inclusive) range and M and N define the size of the output array (rows
and columns, respectively).
The resulting histogram should be nearly flat from 10 to 17. Pay particular attention to the
endpoints of the distribution.
Test your function with the following pieces of code:
• x = randint(-30,5,100000,1);
hist(x,-30:5)
• x = randint(-45,-35,100000,1);
hist(x,-45:-35)
• x = randint(7,-2,100000,1);
hist(x,-2:7)
2. Modify your code to allow for missing/default inputs. Use the behavior of rand to help design
your code. You will need to use nargin in your routine. For example, the function should be able
to return
Exercise 52 Use rand function to generate 100 random numbers. Treating the numbers less than or
equal to 0.5 as zero and the other half as 1, (simulate the experiment of a coin toss (1-Heads) and
0-Tails). Starting from 10, increase the numbers in steps of ten and establish how many numbers one
needs to reach the case of an unbiased coin.
Exercise 53 Generate three sets of random numbers. For the first set, create zeros and ones as
described in previous exercise. For the second set, generate uniform random numbers in the range
[0, 2] and take zero to be all the numbers less than or equal 0.5 and the rest to be 1. For the third set,
generate uniform random numbers in the range [0, 3] take zeros to come from all numbers less than or
equal to 0.5 and the rest to be 1. Can you explain what the probabilities of zeros and 1s in the three
sets mean?
Exercise 54 Generate
p two groups of 100 uniform random numbers (xi and yi , i = 1, 2, . . . , 100). Now
compute zi = −2 ln(xi ) cos π(2yi − 1). Plot a histogram of zi and compare it to the normal pdf (Hint:
use histfit).
Exercise 55 Generate a set of Poisson distributed random numbers (means ranging from 1-10). In-
crease the mean. Observe how the histogram changes. For example, generate a Poisson number set
with a mean of 25. Generate a Gaussian set with a mean of 25 and standard deviation of 5. Compare
this Gaussian random number set to the Poisson with mean equal to 25.
52 13.1 Linear equations
13. Equations
This section briefly describes how to resolve linear and non-linear equation systems in Matlab.
is described as a matrix:
A·x=b
where A is the matrix of coefficients, x is the vector of unknowns and b is the vector of indepen-
dent coefficients.
The norm of a matrix measures its size and in Matlab it is calculated with the norm (p,A)
command where p = 1, 2 . . . indicates the order of the norm.
The range of a matrix is calculated with the rank(A) command.
The fundamental tool for resolving a system of linear equations in Matlab is the \ operator which
also resolves the more general system A · x = B where B is a matrix with m columns and, in this
case, the m systems are resolved for each column.
The possible cases in an A · x = b system are that the system is square (same number of equa-
tions and unknowns), under-determined (fewer equations than unknowns) and over-sized (more
equations than unknowns).
• Square
If the square matrix A is not singular, the system can be resolved in two ways:
– x = A\b
– x = inv(A) · b
Matlab recognizes two special cases: when the matrix A is defined positive and when A is
triangular12 .
• Over-determined
Matrix A is a matrix with the form m × n with m > n. In this case, the system may or may not
have a solution.
– If rank(A) = n, then x = A\b returns the solution for minimum squares (the residual of
A · x − b is minimized).
– If rank(A) < n, then x = A\b obtains a basic solution.
• Under-determined
Matrix A is a matrix with the form m × n with m < n. In this case, the system may have one
or an infinite number of solutions. The solution x = A\b will be a solution with, at most, a
non-null number k of elements where k is the range of the matrix A.
Some Matlab functions for factorizing matrices are:
12 See the help facility for further information.
13.2 Polynomials 53
– [U, S, V]=svd(A) breakdown in singular values of the matrix A. The matrices U and V
are unitary matrices and the matrix X is the diagonal matrix.
13.2 Polynomials
it is sufficient to write a vector row with the coefficients of the polynomial ordered:
v = [a1 , a2 , . . . , an , an−1 ].
Matlab has the roots function to calculate the roots of a polynomial. Applied to the coefficients
vector, it returns the roots of the polynomial. To calculate the value of a polynomial in a point x,
Matlab has the polyval(p,x) function where p is the coefficients vector of the polynomial.
Given n points in the plane, (xk , yk ), k = 1, . . . , n, with distinct xk , there is a unique polynomial
in x of degree less than n whose graph passes through the points. This polynomial is called the
interpolating polynomial because it exactly reproduces the given data:
P (xk ) = yk k = 1, . . . , n
The most compact representation of the interpolating polynomial is the Lagrange form
X Y x − xj
P (x) = yk
xk − xj
k j6=k
The coefficients of an interpolating polynomial using its power form as the following,
x1n−1 x1n−2
... x1 1 c1 y1
x2n−1 x2n−2 ... x2 1 c2 y2
.. .. .. .. .. = ..
. . ... . . . .
xnn−1 xnn−2 ... xn 1 cn yn
The matrix V (the first matrix) of this linear system is known as a Vandermonde matrix. The
function vander generates Vandermonde matrices.
54 13.3 The interpolating polynomial
Example 23.
Given a set of points, create a polynomial and obtain the Vandermonde matrix.
>> x=0:3;
>> y=[-5 -6 -1 16];
>> disp([x; y])
Lagrange form:
Vandermonde matrix:
>> V=vander(x);
Solution
>> c=V\y’;
The power form and the Vandermonde matrix is a satisfactory technique for problems involving
a few well-spaced and well-scaled data points. But as a general-purpose approach, it is dangerous.
We will see some Matlab interpolation functions. Our first function is based on the Lagrange
form:
function v=polyinterp(x,y,u)
n=length(x);
v=zeros(size(u));
for k=1:n
w=ones(size(u));
for j=[1:k-1 k+1:n]
w=(u-x(j))./(x(k)-x(j)).*w;
end
v=v+w*y(k);
end
Example 24.
>> x=0:3;
>> y=[-5 -6 -1 16];
>> symx=sym(’x’);
>> P=polyinterp(x,y,symx);
>> pretty(P)
>> p=simplify(P)
13.3 The interpolating polynomial 55
Example 25.
>> x=1:6;
>> y=[16 18 21 17 15 12];
>> display([x; y]);
>> u=.75:.05:6.25;
>> v=polyinterp(x,y,u);
>> plot(x,y,’o’,u,v,’-’)
v = interp1(x,y,u,method=’A’)
• v5cubic Cubic interpolation used in MATLAB 5. This method does not extrapolate. If x is not
equally spaced, ’spline’ is used.
56 13.4 Integration and Differentiation
Example 26.
The two most important functions in Matlab for calculating integrals numerically are quad and
quadl, which use the Simpson and Lobato quadratures, respectively, to estimate the integral.
The most common Matlab function for calculating derivatives is the diff command that allows
derivatives to be obtained for the order required numerically.
Consult the Matlab guide for more information on numerical integration and differentiation.
This part of the manual describes how to use Matlab to solve non-linear algebraic equations of
single and multiple variables using the fzero and fsolve functions/routines from the optimization
toolbox.
The Matlab fzero function can be used to solve a single variable nonlinear equation of the form
f (x) = 0. The equation must first be programmed as a function (in an m-file).
The solution arrived out depends on the initial guess x0.
x = fzero(fun,x0) tries to find a zero of function “fun” near to x0, if x0 is a scalar. fun is a
function handle for either an M-file function or an anonymous function.The value x returned by
fzero is near a point where fun changes sign, or NaN if the search fails. In this case, the search
ends when the search interval is expanded until an Inf, NaN, or complex value is found.
To see how the fzero function works, we solve the following equation in Example 1:
13.5 Non-linear equations 57
y = x3 − 5x2 − x + 5;
Example 27.
Go to “File”, select “New”, select “M-File”. Create a function with the variables and the
equation we want to solve in an M-file by typing the following:
function y= example(x)
y = x3 − 5x2 − x + 5;
Note: The file name and the function name must be the same. In the above example, we
have chosen “example.m” as the filename and the function name.
Create a script (M-file) that calls this function and that includes the fzero function.
>>fzero(@example,4)
or, equivalently
>>fzero(@(x)example(x),4)
Note: The @ symbol is used to create a function handle. It is also used at the start
of directory names containing Matlab object methods and the constructor for the object,
e.g. the directory @inline contains the constructor inline.m for the inline object and all
methods for inline objects.
• −3 NaN or Inf function value was encountered during search for an interval containing a sign
change.
• −4 Complex function value was encountered during search for an interval containing a sign
change.
The fsolve routine is more general and solves systems of nonlinear equations of several variables.
It uses a quasi-Newton method13 . fsolve tries to solve equations of the form F (X) = 0 where F and
X may be vectors or matrices. The user must supply a routine to evaluate the function vector.
• x = fsolve(fun,x0) starts at x0 and tries to solve the equations described in function fun.
13 See Matlab help facility for further information.
58 13.6 Solving One equation
You can type >> help fsolve in the Command Window for a more detailed description.
The best way to learn is by doing, so here are some equations to solve.
We can either use the fzero or fsolve routines. In the following exercises we will only use fsolve
(try re-writing the same exercise with fzero by yourself).
We start by solving a simple non-linear equation such as:
exp(x) = 6 − x2 ;
Steps to follow:
1. Go to “File”, select “New”, select “M-File”. Create a function with the variables and the equation
that we want to solve in an m-file. Remember to give the m file the same name as the function.
In our example, equation.m
function F = equation(x)
F = exp(x)-6+xˆ2;
2. Create a script (M-file) that calls the above-defined function and includes the fsolve function.
Next, we include some parameters whose values we want to be able to change. Try solving the
following equation when a = 2 and b = 1.
ax = 7 − ln x − b
13.8 Solving Two equations with parameters 59
function[sol]=example_fsolve2(x,a,b)
sol=a*x+log(x)+b-7;
fsolve(@(x)example_fsolve2(x,2,1),2)
ax2 + by 2 = 3
y − 1 = cx3 + 5x2 + dx
function[sol]=twoequation(x,a,b,c,d)
sol(1)=a*x(1)ˆ2+b*x(2)ˆ2-3;
sol(2)=x(2)-1-c*x(1)ˆ3-5*x(1)ˆ2-d*x(1);
and, for (a,b,c,d)=(1,1,1,1) values and (x,y)=(1,1) initial values, we obtain the following
solution:
s=fsolve(@(x)twoequation(x,1,1,1,1),[1,1])
and, therefore,
than options.TolFun.
s =
0.2836 1.7087
Try solving the above system assigning different values to the parameters a and b.
We show you here how to solve dynamic equations. Suppose that the yt variable, for each period of
time t = 0, 1, . . ., takes the values following the recursive equation:
(1+θ)
(1 + α)yt+1 + βyt4 ω λytα
yt+1 = 1+ω
(γ + 1)yt+1 1+β
aux1=(1+alpha)*ynewˆ(1+theta)+beta*yoldˆ(4*omega);
aux2=(gamma+1)*ynewˆ(1+omega);
aux3=lambda*yoldˆalpha/(1+beta);
F=ynew-aux1*aux3/aux2;
yini=123;
alpha=.2;
beta=.4;
theta=.5;
omega=.7;
gamma=.5;
lambda=.9;
param=[alpha beta theta omega gamma lambda];
y(1)=yini;
for t=2:30
yold=y(t-1);
y(t)=fsolve(@(x)eqndynamic1(x,param,yold),100);
end
y
plot([1:30],y)
13.10 Exercises
Exercise 56 Given the matrix of coefficients A and the vector of independent variables b, calculate
the solution of the system of linear equations Aẋ = b. First of all, calculate the of range of the matrix
of coefficients and check that the solution you obtain is correct.
a)
7 3 0 3
9 4 2 6
A=
2
6 8 9
5 1 7 1
b= 1 4 5 8
b)
7 3 0 10
9 4 2 13
A=
2
6 8 8
2 1 7 3
b= 1 4 5 8
13.10 Exercises 61
c)
7 3 0 3 3 7
9 4 2 6 2 5
A=
2
6 8 9 1 3
5 1 7 1 9 4
b= 1 1 0 0
Exercise 57 Use the functions fzero and fsolve to solve the following equations:
a)
3x + ex + 5
b)
2x + sin(x) − 7
c)
y = p1 x + sin(p2 x) − ep3 x + p4
where the vector is p = (1 3 5 2).
d)
y 2 + x2 = 49
x + 3y − sin(x) = 2.
ytβ + (1 + α)yt+1
γ β
+ A yt+1
yt+1 = .
(1 + β)yt1−γ (B + 1)
Exercise 59 Tom and Ben are boys and here is a table of their weights, in pounds and ounces, over
their first few months.
You can use datenum to convert the date in the first three columns to a serial date number measuring
time in days. t = datenum(W(:,[3 1 2]));
Make a plot of their weights versus time, with circles at the data points and the pchip interpolating
curve in between. Use datetick to relabel the time axis. Include a title and a legend.
Exercise 60 Interpolate these data by each of the four methods of the function interp1 . Plot the
results for −1 ≤ x ≤ 1.
62 14.1 Financial Time Series toolbox
x y
-1.00 -1.0000
-0.96 -0.1512
-0.65 0.3860
0.10 0.4802
0.40 0.8838
1.00 1.0000
What are the values of each of the four interpolates at x = −0.3? Which of these values do you prefer?
Why?
The data were actually generated from a low-degree polynomial with integer coefficients. What is
that polynomial?
figure('position',get(0,'screensize'))
axes('position',[0 0 1 1])
[x,y] = ginput;
Place your hand on the computer screen. Use the mouse to select a few dozen points outlining your
hand. Terminate the ginput with a carriage return. You might find it easier to trace your hand on a
piece of paper and then put the paper on the computer screen. You should be able to see the ginput
cursor through the paper. Now think of x and y as two functions of an independent variable that goes
from one to the number of points you collected. You can interpolate both functions on a finer grid and
plot the result with
n = length(x);
s = (1:n)';
t = (1:.05:n)';
u = interp1(s,x,'spline');
v = interp1(s,y,'spline');
clf reset
plot(x,y,'.',u,v,'-');
14. Toolbox
In this chapter we will analyze four Matlab toolboxes that are fundamental for financial analysis:
the ‘Financial Times Series Toolbox’, the ‘Statistics toolbox’, the ‘GARCH toolbox’ and the ‘Financial
Toolbox’.
The ‘Financial Time Series Toolbox’ for Matlab is a collection of tools for the analysis of time series
data in the financial markets. The toolbox contains a financial time series object constructor and
several methods that operate on and analyze the object (MathWorks). The best way to understand
its use, is to work with it. Therefore we will provide you with a data series called ‘rdtos.xls’ to learn
how to write it as a financial series.
As we have previously seen, there are various ways to import a file from Excel to Matlab, includ-
14.1 Financial Time Series toolbox 63
ing ‘Import data’. The file ‘rdtos.xls’14 has four columns, the first column contains dates and the
rest contains monthly returns on three different assets (an equally weighted Spanish equity index,
a value weighted Spanish equity index and a Spanish corporate debt index). However, when dates
are imported to Matlab, this program does not understand the data as dates and does not maintain
their format. The ‘Financial Time Series toolbox’ is useful for building a financial time series based
on dates imported from Excel (where the dates are saved in numeric format). Once the data have
been imported, Matlab contains a matrix ( we have called it ‘rent’). The first column contains dates
so that for Matlab to read them, they must be converted to date format (we call the series ‘dates’):
dates=datenum(’30-Dec-1899’)+rent(:,1);
The arguments for this last command are dates (the series we called ‘dates’), series (the series
we called ‘rent’), name of series (we have called them ‘first’, ‘second’ and ‘third’), frequency (3 means
monthly)15 and description of the series. The first series can be drawn with the command (It is the
series called ‘first’ in the ‘fts’ financial series):
plot(fts.first)
However, the ‘Financial Time Series toolbox’ has commands that allow the financial series to
be drawn and for working with them such as the chartfts command. Entering chartfts(fts)
displays an interactive graph (Figure 9) on the screen (the three series are plotted). This graph
allows the series to be combined in order to draw them two by two or the three together (see the
help and the Char Tools command).
Another utility provided by this toolbox is the possibility of changing the dates according to the
frequency of the available data. The financial time series built with fts has a monthly frequency.
Let’s see now how to move to continuous compound returns.
Given
14 These series are from Gil (2006).
15 Check Matlab help for further frequency information.
64 14.2 Statistics toolbox
Therefore, to pass from the monthly financial series to the continuous compound, it is enough to
construct
cfts=log(1+fts);
Suppose we now wish to construct a series of quarterly returns, that is, the first value will be
the average return of the returns in the first quarter of 1971 and so on, that is,
qfts=3*toquarterly(cfts);
There are other commands of this type such as toannual, tosemi,... which, suitably used,
provide a series of annual and half yearly compound returns.
Although the ‘Financial Time Series toolbox’ is useful for working with dates, the format of the
financial series is not useful for working with the data. Therefore, it is useful to convert them into
matrices for handling them. The following command converts a time series into a matrix
cftsmat=fts2mat(cfts);
which builds a data matrix from the cfts time series without considering the dates column.
The Statistics Toolbox provides a comprehensive collection of tools to assess and understand data
in Matlab. It includes functions and interactive tools for modeling data, analyzing historical trends,
simulating systems, developing statistical algorithms, and learning and teaching statistics. The
toolbox supports a wide range of statistical tasks, from random number generation to calculating
basic descriptive statistics, designing of experiments and statistical process control or developing
and visualizing multidimensional nonlinear models. It offers a rich set of statistical plot types and
interactive graphics, such as polynomial fitting and response surface modeling (MathWorks). Let’s
see some examples to understand how to use it better.
14.2 Statistics toolbox 65
Example 28.
Calculate the first four sample moments of the annual (it must be built first) and contin-
uous returns. State whether there is evidence that the assets follow a lognormal distribu-
tion.
afts=12*toannual(cfts); aftsmat=fts2mat(afts);
moment\_afts=[mean(aftsmat) var(aftsmat) skewness(aftsmat) ...
kurtosis(aftsmat)];
moment\_cfts=[mean(cftsmat) var(cftsmat) skewness(cftsmat) ...
kurtosis(cftsmat)];
For the assets to be considered as following a lognormal distribution, the sample moments
of the returns must be, approximately, 0, 1, 0 and 3, respectively.
Another indicator of normality would be the histogram which, in Matlab, can be obtained
together with a normal one. In the case of our example, a first series of continuous
compound returns is drawn using 100 blocks. The commands described for plot are
also valid for the histogram.
histfit(cftsmat(:,1),100)
There is a large number of functions in the Matlab ‘Statistics Toolbox’ that can be useful, classi-
fied in groups. The following ones are notable among them:
2. Statistical Display: graphics for checking the distribution of statistics and the sample. For
example, normplot.
Example 29.
Yi = m(Xi ) + εi i = 1, . . . , N
Yi ≡ escalar Xi ≡ vector
εi ∼ N (0, σ) m(Xi ) ≡ conditional mean of Y
Example 30.
Given the variables Y and X, calculate the coefficients α, β1 and β2 of the following regres-
sion:
Y = α + β1 X + β2 X 2 .
Z=[ones(length(X),1) X X.ˆ2];
[b,bint,r,rint,stat]=regress(Y,Z);
Yhat=b(1)*Z(:,1)+b(2)*Z(:,2)+b(3)*Z(:,3);
plot(1:length(Y),Y)
hold on
plot(1:length(Y),Yhat,’r’)
As well as the functions in the Matlab toolboxes, there is a large number of programs distributed
free on the Internet that can be useful. In the case of regressions, see the page of James P. LeSage16 ,
which contains numerous functions on regressions such as, for example, to check for heterocedas-
ticity, etc.
16 www.spatial-econometrics.com
14.3 GARCH toolbox 67
The ‘GARCH Toolbox’ provides an integrated computing environment for modeling the volatility of
univariate economic time series. It uses a general ARMAX/GARCH composite model to perform
simulation, forecasting, and parameter estimation of univariate time series in the presence of con-
ditional heteroskedasticity. Supporting functions perform tasks such as pre- and post-estimation
diagnostic testing, hypothesis testing of residuals, model order selection, and time series trans-
formations. Graphics capabilities let you plot correlation functions and visually compare matched
innovations, volatility, and return series (MathWorks).
It is important to model the volatility of assets in financial applications. Observing the volatility
of the returns of assets, it can be seen that they almost always have some of the following properties:
ARIMA models are usually used to study the behavior of financial series. In Matlab, most of
these models are implemented in the ‘GARCH toolbox’.
Some of the functions are used for carrying out a prior analysis are:
1. [ACF,Lags,Bounds] = autocorr(Series,nLags,M,nSTDs)
Calculates and draws the autocorrelogram (ACF) with confidence intervals.
2. [PartialACF,Lags,Bounds] = parcorr(Series,nLags,R, nSTDs)
Calculates and draws the partial autocorrelogram (PACF) with confidence intervals.
3. [H, pValue, Qstat, CriticalValue] = lbqtest(Series, Lags,...
Alpha, DoF)
Matlab also allows a series to be estimated using GARCH models using the following series:
Returns the coefficients, committed standard errors and the statistics for the calculated GARCH
model.
3. garchplot(Innovations,Sigmas,Series)
Draws the errors of the estimation, the volatility and the returns.
68 14.3 GARCH toolbox
Here you have an example of modeling a series with a GARCH model using Matlab. The analysis is
divided into four steps:
1. Pre-estimation analysis.
3. Post-estimation analysis.
1. Pre-estimation analysis
Before choosing a model to estimate the parameters, it is necessary to carry out a prior study
on the properties of the series to be estimated to ensure that the model under consideration
is in fact suitable. For example, there is no point in modeling a series whose volatility is
constant with a GARCH model that proposes volatility that changes over time since this would
lead to an unnecessary effort and the solution thus obtained may not be optimal (convergence
problems,. . . ). To prevent these problems, it is useful to carry out a pre-estimation analysis
considering the drawing of the series to be estimated, the correlogram, etc, that allows the
presence of ARCH effects to be checked. This prevents convergence problems by choosing the
simplest model that suitably describes the series.
The steps in this section are, firstly, to obtain the series of returns from the series of prices
and check that there is a correlation and how much it is. The series of prices is that provided
by the Matlab series ‘garchdata, NASDAQ’:
autocorr(serie)
parcorr(serie)
These two graphs give us an idea of the autocorrelation that exists. As a preliminary anal-
ysis, these graphs give us an idea of the correlation properties in the returns, showing
whether it is necessary to model the series with any structure of the conditional expecta-
tion.
d) Although the autocorr and parcorr graphs show a small correlation, it is not very sig-
nificant. The autocorrelogram of the squared returns shows whether or not there is cor-
relation and persistence in the second order moment.
autocorr(serie.ˆ2)
parcorr(serie.ˆ2)
On seeing the graphs, it can be concluded that the returns have no correlation on average
and that the variance shows a certain correlation that appears to drop off over time,
indicating the possibility that the variance is not stationary.
14.3 GARCH toolbox 69
e) Quantification of the correlation is done using the Ljung-Box-Pierce test and the Engle
test (lbqtest and archtest, respectively). The lbqtest function implements the Q-test
to see if there is randomness in the series based on the data. Generally, it is also used in
the post-estimation analysis to check that the residuals are white noise. In this case, it
will be used since, by default, the GARCH model implemented in Matlab assumes that the
returns are a constant plus noise. Under the null hypothesis, the statistics follow a χ2 .
The archtest function calculates the Engle test to check for ARCH affects. Under the null
hypothesis, it is assumed that the series is a random Gaussian sequence (that is, there
are no ARCH effects), the statistic is a χ2 .
Both lbqtest and archtest functions have the same outputs, a H = 0, 1 value showing
whether the null hypothesis is rejected or not, the p-value, the statistical and the critical
values.
Both functions are calculated, the first with the returns series and the second with the
squared series. In both cases the average of the series must be subtracted using the lags
10, 15, 20 at a 5% significance level.
[H,pvalor,estad,v_crit]=
lbqtest(serie-mean(serie),[10 15 20]’,0.05)
To prove the assumption that the series of returns is a constant plus noise, the value of
H must be zero. However, it is 1 so that, instead of calculating a normal GARCH, one that
incorporates this effect must be calculated, an AR(1) + GARCH(1, 1).
[H,pvalor,estad,v_crit]=
lbqtest((serie-mean(serie)).ˆ2,[10 15 20]’,0.05)
[H,pvalor,estad,v_crit]=
archtest(serie-mean(serie),[10 15 20]’,0.05)
The Matlab default model (GARCH(1, 1))17 is applied using the garchfit command.
[Coef,error,LLF,innov,sigmas,summary]=garchfit(serie)
Once the model is estimated, the parameters, their deviation and the T-statistic can be seen
using the command
garchdisp(coef,error)
3. Post-estimation analysis
We can see if the estimation model has been chosen well by studying the residuals, the stan-
dard deviations and the observed returns.
17 GARCH(1,1)
y t = C + εt .
σt2 = κ + G1 σt−1
2
+ A1 ε2t−1 .
70 14.3 GARCH toolbox
a) Compare the residuals, the standard deviations and the returns. The garchplot function
allows the relationships between the residuals (innov), the deviations (sigmas) and the
returns to be inspected.
garchplot(innov,sigmas,serie)
Note that the sum of the GARCH coefficients is almost 1 (CoefGARCH + CoefARCH ) which
implies that there is integration. Further, it appears that the residuals and the series
show volatility conglomerates, that is, there are periods when high or low volatility pre-
dominates.
b) Draw and compare the correlation of the standardized innovations. Although in the previ-
ous figure we have seen the existence of volatility conglomerates in the residuals, we will
draw the standardized innovations (the innovations divided by their conditional standard
deviation) to see if stability appears.
plot(innov./sigmas)
ylabel(’errors’)
title(’Standard errors’)
Draw the autocorrelogram of the squared returns to see if there is a correlation.
autocorr((innov./sigmas).ˆ2)
If this graph is compared to those obtained previously (autocorrelogram of the squared
series) it can be seen that this model explains the heterocedasticity of the returns. What
happens with the autocorrelogram of the standard errors? Remember that we said that
our series showed an AR component which we have not modeled.
autocorr((innov./sigmas))
c) Quantify and compare the correlation of the standard errors. This can be done with the
Q-test and the ARCH-test applied to the series of the standardized residuals.
[H,pvalor,estad,v_crit]=lbqtest((innov./sigmas).ˆ2,...
[10 15 20]’,0.05)
[H,pvalor,estad,v_crit]=archtest(innov./sigmas,...
[10 15 20]’,0.05)
Previously, H = 1 was obtained, which implied that there was evidence of GARCH effects.
Now, on the other hand, the value of H is zero which confirms the explanatory power of the
model with regard to GARCH effects. However, it still does not model the autoregressive
part of the residuals.
[H,pvalor,estad,v_crit]=lbqtest(innov./sigmas,...
[10 15 20]’,0.05)
spec=garchset(’P’,1,’Q’,1,’R’,1)
[Coef,error,LLF,innov,sigmas,resumen]=garchfit(serie)
garchdisp(coef,error)
Finally, it remains to check that this model does cover all the properties of the series.
[H,pvalor,estad,v_crit]=lbqtest(innov./sigmas,[10 15 20]’,0.05)
[H,pvalor,estad,v_crit]=lbqtest((innov./sigmas).ˆ2,...
[10 15 20]’,0.05)
[H,pvalor,estad,v_crit]=archtest(innov./sigmas,...
[10 15 20]’,0.05)
14.4 Optimization toolbox: Examples 71
The ‘Optimization Toolbox’ extends the MATLAB technical computing environment with tools and
widely used algorithms for standard and large-scale optimization. These algorithms solve con-
strained and unconstrained continuous and discrete problems. The toolbox includes functions for
linear programming, quadratic programming, nonlinear optimization, nonlinear least squares, solv-
ing systems of nonlinear equations, multi-objective optimization, and binary integer programming
(MathWorks).
min f (x)
x
where
To solve this with Matlab, a file must first be created with the same name as the function defined
in it. For example, the file ‘funct1.m’:
Once the file has been created, the routine for minimization without restrictions is called
This can be solved with the fmincon command which allows the use of inequalities all for the
type c(x) ≤ 0 , so that the first thing to do is to re-write the second inequality
x1 x2 ≥ −10 =⇒ −x1 x2 − 10 ≤ 0
Once the inequality is rewritten, a file must be created with the function and another with the
bound constraints. The file ‘funct1.m’, defined previously, will be used for the function and the file
‘conditions1.m’ will be created for the conditions.
% inequality conditions
cond = [1.5+x(1)*x(2)-x(1)-x(2); -x(1)*x(2)-10];
% equality conditions
condeq = [];
x0=[-1,1];
% we will use a standard minimization algorithm
options=optimset('LargeScale','off');
[x,fval,exitflag,output, lambda, grad,hessian] = ...
fmincon(@funct1,x0,[],[],[],[],[],[],@conditions1,options)
The variable of interest x can be restricted with bounds (both upper and lower) within the minimiza-
tion function
x=fmincon(@funct1,x0,[],[],[],[],lb,ub,@conditions1,options)
where
lb ≤ x ≤ ub
For example, in the previous case, suppose we want to find a solution with x1 ≤ 0 and x2 ≤ 0,
then
x0=[-1,1];
% we will use a standard minimization algorithm
options=optimset('LargeScale','off');
[x,fval,exitflag,output, lambda, grad,hessian] = ...
fmincon(@funct1,x0,[],[],[],[],lb,ub,@conditions1,options)
minf (x)
x
s.t. c(x) ≤ 0
ceq(x) = 0
A·x≤b
Aeq · x = beq
lb ≤ x ≤ ub
the syntax is
fmincon(@fun,x0,A,b,Aeq,beq,lb,ub,@cond_nolineal,options)
14.4 Optimization toolbox: Examples 73
Generally, the gradient of the function is calculated numerically when it is minimized. However,
this gradient can be defined analytically and thus the problem will be resolved more efficiently. For
this, a file is written containing the function and its gradient. We will use the previous function and
calculate its gradient in the file ‘funct1bis.m’:
function[sol, solgrad]=funct1bis(x)
% the previous function
sol = exp(x(1))*(4*x(1)ˆ2+2*x(2)ˆ2+4*x(1)*x(2)+2*x(2)+1);
% the gradient
solgrad = [sol+exp(x(1))*(8*x(1)+4*x(2)),...
exp(x(1))*(4*x(1)+4*x(2)+2)];
Then we will write a file with the function’s and gradient’s conditions, ‘conditions1bis.m’
x0=[-1,1];
% we will use a standard minimization algorithm
options=optimset('LargeScale','off');
% add the calculated gradient
options = optimset(opciones, 'Gradobj','on','GradConstr','on');
[x,fval,exitflag,output, lambda, grad,hessian] = ...
fmincon(@funct1bis,x0,[],[],[],[],[],[],@conditions1bis,options)
Given the analytic gradient, a check can be made with the numeric gradient using the ‘Deriva-
tivecheck’ option:
Firstly, before carrying out the minimization, Matlab checks if the analytic gradient matches the
numerical one and if not, returns an error message.
To resolve this problem, the file ‘funct2.m’ is created with the function that depends on the
parameter a1 and the file ‘conditions2.m’ with the conditions that depend on the parameter a2 .
74 14.5 Financial toolbox
Finally, before calling the minimization routine, the values of the parameters are defined:
Finally, if we want to maximize a function instead of minimizing it, it is enough to consider −f (x)
instead of f (x).
To define the conditions of the problem suitably, remember the following equivalents:
The ‘Financial Toolbox’ extends Matlab, the ‘Statistics Toolbox’, and the ‘Optimization Toolbox’ with
functions for mathematical and statistical analysis of financial data. Using Financial Toolbox soft-
ware you can optimize portfolios, estimate risk, analyze interest rate levels, price equity derivatives,
and handle financial time series (MathWorks).
14.5.1 Put and call option pricing according to the Black-Scholes model
There are functions in Matlab that calculate the value of put and call options, both European
(Black-Scholes model) and American (binomial model).
7. The interest rate is constant and the same for all maturities.
Suppose we have one European call and another European put and we calculate their price as
well as the Greeks (measurements of the option’s sensitivity to changes in any of its components).
For example, given the following data:
volcall = blsimpv(100,95,0.10,0.25,Ocall)
volput = blsimpv(100,95,0.10,0.25,Oput)
The binomial model considers that the probability of each possible price of the asset at each instant
in time follows a binomial distribution (the price of the asset St may rise to Su or drop to Sd at time
t + 1 ). This model is applied to American options with the same properties as the European ones
except they can be exercised at any time. Therefore, assume the following parameters:
Further, the option is a call that pays a single dividend after three periods. Given that the
maturity is 1/4 of the year and ∆t = 0.05 , there are 0.25/0.05 = 5 periods. To calculate the price of
the American call with these data:
[PrecioS,PrecioCall]=binprice(100,95,0.10,0.25,0.05,0.5,1,0,5,3)
15. Exercises
1. Generate a random
• real number in the range (0, 20)
• real number in the range (20, 50)
• integer in the inclusive range from 1 to 10
• integer in the inclusive range from 0 to 10
• integer in the inclusive range from 50 to 100.
76 14.5 Financial toolbox
2. Get into a new Command Window and type rand to get a random real number. Make a note of
the number. Then exit MATLAB and repeat this, again making a note of the random number;
it should be the same as before. Finally, exit MATLAB and again get into a new Command
Window. This time, change the seed before generating a random number; it should be different.
3. Create two variables x and y and store numbers in them. Write an expression that would be
true if the value of x is greater than 5 or if the value of y is less than 10, but not if both of
those are true.
4. The geometric mean g of n numbers xi is defined as the nth root of the product of xi:
√
g= n
x1 x2 x3 . . . xn
(This is useful, e.g., in finding the average rate of return for an investment, which is something
you’d do in engineering economics.) If an investment returns 15% the first year, 50% the
second, and 30% the third year, the average rate of return would be (1.15 ∗ 1.50 ∗ 1.30)1/3 ).
Compute this.
5. Give the MATLAB expression that would create a vector (in a variable called vec) of 50 elements
that range, equally spaced, from 0 to 2π
6. Write an expression using linspace that will result in the same as 2 : 0.2 : 3.
7. Write an expression that refers to only the odd-numbered elements in a vector, regardless of
the length of the vector. Test your expression on vectors that have both an odd and an even
number of elements.
9. Create a variable rows that is a random integer in the inclusive range from 1 to 5. Create a
variable cols that is a random integer in the inclusive range from 1 to 5. Create a matrix of all
zeros with the dimensions given by the values of rows and cols.
10. Create a 3x5 matrix of random real numbers. Delete the third row.
11. Create a three-dimensional matrix with dimensions 2 x 4 x 3 in which the first ’layer’ is all 0s,
the second is all 1s, and the third is all 5s.
12. Find the sum of the first n terms of the harmonic series where n is an integer greater than
one.
1 1 1
1 + + + + ...
2 3 4
13. Find the sum of the first five terms of the geometric series
1 1 1
1+ + + + ...
2 4 8
14. Find the following sum by first creating vectors for the numerators and denominators:
3 5 7 9
+ + + s
1 2 3 4
15. Create a vector of five random integers, each in the inclusive range from e10 to 10. Perform
each of the following: a) subtract 3 from each element b) count how many are positive c) get
the absolute value of each element d) find the maximum.
14.5 Financial toolbox 77
16. A vector v stores, for several employees of the Green Fuel Cells Corporation, the hours they’ve
worked one week followed for each by the hourly pay rate. For example, if the variable stores
that means the first employee worked 33 hours at $10.50 per hour, the second worked 40
hours at $18 an hour, and so on. Write code that will separate this into two vectors: one
that stores the hours worked and another that stores the hourly rates. Then, use the array
multiplication operator to create a vector, storing in the new vector the total pay for every
employee.
37. For the following vectors and matrices A, B, and C:
4 1 −1 2
A= B= 1 4 C=
2 3 0 3
Perform the following operations, if possible. If not, just say it can’t be done! A ∗ B,B ∗ C, C ∗ B
17. Generate a vector of 20 random integers, each in the range from 50 to 100. Create a variable
evens that stores all of the even numbers from the vector and a variable odds that stores the
odd numbers.
18. Write an input statement that will prompt the user for a real number and store it in a variable.
Then, use the fprintf function to print the value of this variable using two decimal places.
19. If the lengths of two sides of a triangle and the angle between them are known, the length of
the third side can be calculated. Given the lengths of two sides (b and c) of a triangle, and the
angle between them a in degrees, the third side a is calculated as follows:
a2 = b2 + c2 + 2bc cos(a)
Write a script thirdside that will prompt the user and read in values for b, c, and a (in degrees),
and then calculate and print the value of a with three decimal places. The format of the output
from the script should look exactly like this:
>> thirdside
Enter the first side: 2.2
Enter the second side: 4.4
Enter the angle between them: 50
The third side is 3.429
For more practice, write a function to calculate the third side, so the script will call this
function.
20. Plot sin(x) for x values ranging from 0 to π (in separate Figure Windows): a) using 10 points in
this range b) using 100 points in this range.
21. Generate a random integer n, create a vector of the integers 1 through n in steps of 2, square
them, and plot the squares.
22. Create a 3 x 6 matrix of random integers, each in the range from 50 to 100. Write this to a
file called randfile.dat. Then, create a new matrix of random integers, but this time make it a
2 x 6 matrix of random integers, each in the range from 50 to 100. Append this matrix to the
original file. Then, read the file in (which will be to a variable called randfile) just to make sure
that worked!
23. Write a fives function that will receive two arguments for the number of rows and columns,
and will return a matrix with that size of all fives.
24. Write a function isdivby4 that will receive an integer input argument, and will return logical 1
for true if the input argument is divisible by 4 or logical false if it is not.
78 14.5 Financial toolbox
25. A function can return a vector as a result. Write a function vecout that will receive one integer
argument and will return a vector that increments from the value of the input argument to its
value plus 5, using the colon operator.
26. The cost of manufacturing n units (where n is an integer) of a particular product at a factory
is given by the equation:
C(n) = 5n2 − 44n + 11
Write a script mfgcost that will: a) prompt the user for the number of units n b) call a function
costn that will calculate and return the cost of manufacturing n units c) print the result (the
format must be exactly as shown below).
Next, write the function costn, which simply receives the value of n as an input argument, and
calculates and returns the cost of manufacturing n units.
27. Many mathematical models in engineering use the exponential function. The general form of
the exponential decay function is:
y(t) = Ae−τ t
where A is the initial value at t = 0 and τ is the time constant for the function. Write a script
to study the effect of the time constant. To simplify the equation, set A equal to 1. Prompt the
user for two different values for the time constant, and for beginning and ending values for the
range of a t vector. Then, calculate two different y vectors using the above equation and the
two time constants, and graph both exponential functions on the same graph within the range
the user specified. Use a function to calculate y. Make one plot red. Be sure to label the graph
and both axes. What happens to the decay rate as the time constant gets larger?
if val >= 10
disp('Hello')
elseif val < 10
disp('Hi')
end
30. Write a function createvecMToN that will create and return a vector of integers from m to n
(where m is the first input argument and n is the second), regardless of whether m is less than
n or greater than n. If m is equal to n, the ’vector’ will just be 1 x 1 or a scalar.
31. Write a script that will generate one random integer and will print whether the random integer
is an even or an odd number. (Hint: an even number is divisible by 2, whereas an odd number
is not; so check the remainder after dividing by 2.)
32. The Beaufort Wind Scale is used to characterize the strength of winds. The scale uses integer
values and goes from a force of 0, which is no wind, up to 12, which is a hurricane. The
following script first generates a random force value. Then, it prints a message regarding what
type of wind that force represents, using a switch statement. You are to re-write this switch
statement as one nested if-else statement that accomplishes exactly the same thing. You may
use else and/or elseif clauses.
14.5 Financial toolbox 79
33. . Re-write the following nested if-else statement as a switch statement that accomplishes
exactly the same result for all possible values. Assume that val is an integer variable that has
been initialized, and that ’ok’, ’xx’, ’yy’, ’tt’, and ’mid’ are functions. Write the switch statement
in the most succinct way.
if val > 5
if val < 7
ok(val)
elseif val < 9
xx(val)
else
yy(val)
end
else
if val < 3
yy(val)
elseif val == 3
tt(val)
else
mid(val)
end
end
34. Create an x vector that has integers 1 through 10, and set a y vector equal to x. Plot this
straight line. Now, add noise to the data points by creating a new y2 vector that stores the
values of y plus or minus 0.25. Plot the straight line and also these noisy points.
35. Write a function sumsteps2 that calculates and returns the sum of 1 to n in steps of 2, where
n is an argument passed to the function. For example, if 11 is passed, it will return 1 + 3 + 5 +
7 + 9 + 11. Do this using a for loop.
36. Write a function prodby2 that will receive a value of a positive integer n and will calculate and
return the product of the odd integers from 1 to n (or from 1 to n-1 if n is even). Use a for loop.
37. Write a script that will: a) generate a random integer in the inclusive range from 2 to 5 b) loop
that many times to c) prompt the user for a number d) print the sum of the numbers entered
so far with one decimal place.
38. Trace this to figure out what the result will be and then type it into MATLAB to verify the
results.
count = 0;
80 14.5 Financial toolbox
number = 8;
while number > 3
number = number - 2;
fprintf('number is %d\n', number)
count = count + 1;
end
fprintf('count is %d\n', count)
39. Trace this to figure out what the result will be and then type it into MATLAB to verify the
results.
count = 0;
number = 8;
while number > 3
fprintf('number is %d\n', number)
number = number - 2;
count = count + 1;
end
fprintf('count is %d\n', count)
40. Write a script (e.g., called findmine) that will prompt the user for minimum and maximum
integers, and then another integer which is the user’s choice in the range from the minimum to
the maximum. The script will then generate random integers in the range from the minimum
to the maximum until a match for the user’s choice is generated. The script will print how
many random integers had to be generated until a match for the user’s choice was found.
41. Write a function that will receive a matrix as an input argument, and will calculate and return
the overall average of all numbers in the matrix. Use loops, not built-in functions, to calculate
the average.
42. Create a 3 x 5 matrix. Perform each of the following using loops (with if statements if neces-
sary): a) find the maximum value in each column b) find the maximum value in each row c)
find the maximum value in the entire matrix.
43. Create a vector of 5 random integers, each in the inclusive range from e10 to 10. Perform each
of the following using loops (with if statements if necessary): a) subtract 3 from each element
b) count how many are positive c) get the absolute value of each element d) find the maximum.
44. Vectorize this code! Write one assignment statement that will accomplish exactly the same
thing as the given code (assume that the variable vec has been initialized):
result = 0;
for i = 1:length(vec)
result = result + vec(i);
end
45. Vectorize this code! Write one assignment statement that will accomplish exactly the same
thing as the given code (assume that the variable vec has been initialized):
newv = zeros(size(vec));
myprod = 1;
for i = 1:length(vec)
myprod = myprod * vec(i);
newv(i) = myprod;
end
newv % Note: this is just to display the value
14.5 Financial toolbox 81
46. Vectorize this code; write one assignment statement that will accomplish the same thing:
myvar = 0;
[r c] = size(mat);
for i = 1:r
for j = 1:c
myvar = myvar + mat(i,j);
end
end
myvar % Note just to display the contents of myvar
n = 3;
x = zeros(n);
y = x;
for i = 1:n
x(:,i) = i;
y(i,:) = i;
end
48. Write a function that receives an x vector, a minimum value, and a maximum value, and plots
sin(x) from the specified minimum to the specified maximum.
49. The lump sum S to be paid when interest on a loan is compounded annually is given by
S = P (1 + i)n where P is the principal invested, i is the interest rate, and n is the number of
years. Write a program that will plot the amount S as it increases through the years from 1
to n. The main script will call a function to prompt the user for the number of years (and
error-check to make sure that the user enters a positive integer). The script will then call a
function that will plot S for years 1 through n. It will use 0.05 for the interest rate and $10,000
for P.
Use the reshape function to make it a 2 x 2 matrix. Then, write an expression that would refer
to just the last column of this cell array.
51. Create a 2 x 2 cell array using the cell function and then put values in the individual elements.
Then, insert a row in the middle so that the cell array is now 3 x 2.
52. Write an anonymous function to implement the following quadratic: 3x2 − 2x + 5. Then, use
fplot to plot the function in the range from −6 to 6.
53. Write a function that will print a random integer. If no arguments are passed to the function,
it will print an integer in the inclusive range from 1 to 100. If one argument is passed, it is the
max and the integer will be in the inclusive range from 1 to max. If two arguments are passed,
they represent the min and max, and it will print an integer in the inclusive range from min to
max.
54. Create a data file containing 10 numbers. Write a script that will load the vector from the file,
and use subplot to do an area plot and a stem plot with these data in the same Figure Window
(note that a loop is not needed). Prompt the user for a title for each plot.
55. Write a script that will do the following. Create two vectors with 20 random integers in each;
in one the integers should range from 1 to 5 and, in the other, from 1 to 500 (inclusive). For
82 14.5 Financial toolbox
each vector, would you expect the mean and median to be approximately the same? Would
you expect the standard deviation of the two vectors to be approximately the same? Answer
these questions and then use the built-in functions to find the minimum, maximum, mean,
median, standard deviation, and mode of each. Do a histogram for each in a subplot. Run the
script a few times to see the variations.
56. Write a function that will return the mean of the values in a vector, not including the minimum
and maximum values. Assume that the values in the vector are unique. It is okay to use the
built-in mean function. To test this, create a vector of 10 random integers, each in the range
from 0 to 50, and pass this vector to the function.
57. A moving average of a data set x = {x1 , x2 , x3 , x4 , ., xn }is defined as a set of averages of subsets
of the original data set. For example, a moving average of every two terms would be 1/2 ∗
{x1 + x2 , x2 + x3 , x3 + x4 , ., xn−1 + xn }.Write a function that will receive a vector as an input
argument, and will calculate and return the moving average of every two elements. Eliminating
or reducing noise is an important aspect of any signal processing. For example, in image
processing noise can blur an image. One method of handling this is called median filtering.
58. The coefficient of variation is useful when comparing data sets that have quite different means.
The formula is CV = (standard deviation/mean) ∗ 100%. A history course has two different
sections; their final exam scores are stored in two separate rows in a file. For example:
99, 100, 95, 92, 98, 89, 72, 95, 100, 100
83, 85, 77, 62, 68, 84, 91, 59, 60
Create the data file, read the data into vectors, and then use the CV to compare the two
sections of this course.
A function generatevec generates a vector of n random integers (where n is a positive integer),
each in the range from 1 to 100, but all of the numbers in the vector must be different from
each other (no repeats). So, it uses rand to generate the vector and then uses another function
alldiff that will return logical 1 for true if all of the numbers in the vector are different, or
logical 0 for false if not in order to check. The generatevec function keeps looping until it
does generate a vector with n non-repeating integers. It also counts how many times it has to
generate a vector until one is generated with n non-repeating integers and returns the vector
and the count. Write the alldiff function.
60. Find the roots of the equation f (x) = 0 for the following function. Also, create x and y vectors
and plot this function in the range from −3 to 3 to visualize the solution.
f (x) = 3x2 − 2x − 5
14.5 Financial toolbox 83
16. References
[1.-] Garcı́a de Jalón, Javier and José Ignacio Rodrı́guez (2005), “Aprenda Matlab 7.0 como si estu-
viera en primero”, Escuela Técnica Superior de Ingenieros Industriales, Univeridad Politécnica
de Madrid.
[2.-] Gil, Javier (2006),“Introduction to Matlab”, manuscript, University of the Basque Country.
[3.-] Moler, Cleve (2004), “Numerical Computing with MATLAB”
http://www.mathworks.com/ moler/ chapters.html.
[4.-] Perez Lopez, Cesar (2002), “Matlab y sus Aplicaciones en las Ciencias y la Ingenierı́a”, Ed.
Practice Hall.
[5.-] Attaway Stormy (2013), “Matlab: A practical introduction to programming and problem solv-
ing” Third Edition, Ed. Elsevier