2008an Introductory Course in MATLAB
2008an Introductory Course in MATLAB
September 2008
Contents
3 Programming in MATLAB 38
3.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
When MATLAB is started appears, by default, a window divided in three parts or sub-windows
similar to the following figure:
• The most important part of this window is what is called “Command Window”, which
is at the right side of the figure. This window is where MATLAB commands are executed
1
Fortran is a general-purpose, procedural, imperative programming language that is especially suited to
numeric computation and scientific computing.
Introductory course in MATLAB Page 4
and the results are showed. For example, in the figure we can see the way of creating a
matrix of random numbers using the command randn.
• At the left side of the figure, we can see two sub-windows. The upper left window shows
the “Current Directory” and “Workspace” changing each other by clicking on the
corresponding tab. The Current Directory window displays the current folder and its
contents. The Workspace window provides an inventory of all variables in the workspace
that are currently defined, either by assignment or calculation in the Command Window
or by importation.
• Finally, the lower window called “Command History” contains a list of commands that
have been executed within the Command Window.
MATLAB file operations use the current directory and the MATLAB search path as ref-
erence points. Any file we want to run must be either in the Current Directory or on the
Search Path. A quick way to view or change the current directory is by using the current
directory field in the desktop toolbar. See the following figure:
MATLAB uses a Search Path to find m-f iles and other MATLAB related files, which
are organized in directories on our file system. By default, the files supplied with MATLAB
products are included in the search path. These are all of the directories and files under
matlabroot/toolbox, where matlabroot is the directory in which MATLAB was installed. We
can modify, add or remove directories through “File”, “Set Path”, and click on “Add Folder”
or “Add with subfolder”, as showed in the next figure:
Introductory course in MATLAB Page 5
The “m-files” (named after its .m file extension) have a special importance. They are text
(ASCII) files ending in “.m”, these files contain a set of command or functions. In general,
after typing the name of one of these “m-files” in the Command Window and pressing Intro,
all commands and functions defined into the file are sequentially executed. These files can be
created in any text editor. MATLAB has its own m-f ile editor, which allows to create and
modify these files. The following figure shows how this editor look likes.
Let’s stress, before starting with the definition of matrices and vectors, that at any moment
we can access to the help of any command of MATLAB by writing in the Command Window
help followed by the command-name or doc followed by the command-name. The former shows
the help in the Command Window and the latter open a new windows, the “Help” windows,
where shows the help of the command.
Introductory course in MATLAB Page 6
45
In the case that we can get an element from a matrix, for example the element in the second
row, third column of matrix A, we have to enter
>> A(2,3)
the result will be
ans =
6
Finally, in the case that we are interested in more elements of a vector or matrix we use the
notation [start:end]. For example, the first three elements of the second column of the matrix
B
4 3 6 0
5 7 0 4
B= 9 8 2 5
5 1 8 7
4 1 9 2
There exist commands that create special matrices. For example, the command zeros(N,M)
creates a matrix of zeros with dimension N-by-M, the command eye(N) creates an identity
matrix of dimension N, the command ones(N,M) creates a matrix of ones with dimension N-
by-M. For instance, if “b” is a vector, then the command diag(b) creates a diagonal matrix
with the elements of “b”.
In this part of the tutorial we introduce simple algebraical and logical operations.
Algebraical operations
Algebraical operations in MATLAB are straightforward, just enter in the Command Window
exactly the same expression as if one writes it in a paper. For example, multiply two numbers
>> 3*5
divide two numbers
>> 15/3
elevate a number to some power
Introductory course in MATLAB Page 8
>> 2∧ (-4)
When the algebraical operations are with vectors or matrices, the procedure is the same, except
that we have to take into account that inner matrix dimension must agree. For example,
multiply matrix A by B
! !
4 3 6 5 8 3
A= ,B =
5 7 0 1 0 6
it is obtained through
>> inv(A)
ans =
-1 -3 5
1 1.5 -2.5
0 0.5 -0.5
Command Description
abs(a) absolute value of the elements of “a”
clc clear the screen
clear clear all variables and functions from the memory
cumprod(a) creates a vector containing the cumulative product of the elements of “a”
cumsum(a) creates a vector containing the cumulative sum of the elements of “a”
det(A) the determinant of matrix A
eig(A) eigen values and eigen vectors of matrix A
inv(A) the inverse matrix of A
length(a) the number of elements of “a”
prod(a) multiplies the elements of “a”
rank(A) the rank of matrix A
size(A) the dimensions of A
sum(a) returns the sum of the elements of “a”
trace(A) the trace of matrix A
who shows all variables in the Workspace
whos shows all variables in the Workspace with more detail
enter
>> sum(a >= b)
and we will find the result that we are looking for
ans =
5
This is just an example of a very simple logical operation, but one can construct construct
more complex logical sentences. The following table shows some useful logical operator.
Command Description
== equal
∼= not equal
< less than
> greater than
<= less than or equal
>= greater than of equal
& and
| or
xor exclusive or
∼ logical complement
any True if any element of a vector is a nonzero number
all True if all elements of a vector are nonzero
For example, we would like to see if the number of the elements greater than 2, but lower than
7 of the vector “a” is equal to the number of the elements greater than 5, but lower than 10 of
the vector “b”. Then, we enter
>> sum(a > 2 & a < 7) == sum(b > 5 & b < 10)
the result will be
ans =
0
There exist situations in which we want to apply different statements depending on some con-
ditioning. This is easily done with the if statement. The basic structure for an if statement is
the following
if Condition 1
Statement 1
Introductory course in MATLAB Page 11
elseif condition 2
Statement 2
elseif condition 3
Statement 3
...
else
Statement n
end
Each set of commands is executed if its corresponding condition is satisfied. The else and
elseif parts are optional. Notice that the if command checks conditions sequentially, first
condition 1, then condition 2, and so on. But when the one condition is verified the statement
associated with it is executed and the if does not continues verifying the rest of conditions.
For example
>> n = 0; if -1 > 0, n = 1; elseif 2 > 0, n = 2; elseif 3 > 0, n = 3; else, n =
4; end
The value of “n” will be 2 even though the third condition is also true.
When we want to repeat statements, we can use loops. They are constructed using either the
command for or the command while.
For example
>> I = [1:5]; J = [1:5]; A = [];
>> for i = I
for j = J
A(i,j) = 1/(j+i-1)
end
end
Introductory course in MATLAB Page 12
While working, MATLAB saves all variables created or loaded in the Workspace. However,
when we close MATLAB, the Workspace cleans itself, and all these variables are eliminated. If
we are interested in keeping that information, the command save can help us. This command
saves all Workspace variables to a “file”. For example
Introductory course in MATLAB Page 13
There are situations in which we are interesting in saving a variable in a text file. This can
be done with the command save, and using some of its options, for example
>> save filename.txt a -ascii
This syntax creates a text file called “filename.txt”, in the current directory, which contains the
variable “a”. This type of file are loaded using command load as follows
>> load filename.txt
For more details enter help save or doc save in the Command Window.
Now, we introduce a first notion to graphs, the command plot. It creates a graph in which the
elements of the vector/s o matrix/ces used as input are plotted. This command can plot the
elements of one vector “a” versus other vector “b” or the elements of a vector “c” versus their
index. For example
>> x = -3:0.1:7
>> y = 2*x.∧ 2 - 5*x -2
>> plot(x,y)
Introductory course in MATLAB Page 14
Alternatively, we can plot a vector “y” against its own index. In our example we enter
>> plot(y)
It is possible to modify some aspect of the graph like color, width, and shape, change the
ticks of the axes, add other line, using the commands set, hold on and hold off. Moreover,
we can add a tittle, label in the axis, legends, etc. Here is an example
>> x = -pi:0.1:pi; y = sin(x); y1 = cos(x);
>> set(gcf,'Color','w')
>> plot1 = plot(x,y);
>> hold on
>> plot2 = plot(x,y1)
>> hold off
>> set(plot1,'LineStyle','--','LineWidth',2.5, 'Color','r');
Introductory course in MATLAB Page 15
MATLAB has several auxiliary libraries called Toolbox , which are collections of m-f iles that
have been developed for particular applications. These include the Statistics toolbox, the Op-
timization toolbox, and the Financial toolbox among others. In our particular case, we will do
a brief description of the Statistics a Optimization toolboxes and we will use same commands
of the Financial toolbox.
The Statistics toolbox, created in the version 5.3 and continuously updated in newer versions,
is a collection of statistical tools built on the MATLAB numeric computing environment. The
toolbox supports a wide range of common statistical tasks, from random number generation,
Introductory course in MATLAB Page 16
curve fitting, to design of experiments and statistical process control. By typing help stats
on the command window, an enormous list of functions appears. They are classified according
to the topic they are made for. We will revise just a few of them, taking into account their
interest for the first-year courses.
Parametric inferential statistical methods are mathematical procedures for statistical hypothe-
sis testing which assume that the distributions of the variables being assessed belong to known
parametrized families of probability distributions. In that case we speak of parametric models.
When working within this branch of statistics, it is of vital importance to know the properties
of these parametric distributions. The Statistics toolbox has information of a great number of
known parametric distributions, regarding their PDFs, CDFs, ICDFs, and other useful com-
mands to work with. Moreover, the function names were created in a very intuitive way, keeping
the distribution code name unchanged and adding at the end a specific particle for each func-
tion. Thus, for instance, norm is the root for the normal distribution, and consequently normpdf
and normcdf are the commands for finding the density and cumulative distribution functions,
respectively. Below we list some of the well-known parametric distributions and the specific
commands that are already available for each of them.
Introductory course in MATLAB Page 17
Distributions Root name pdf cdf inv fit rnd stat like
Beta beta X X X X X X X
Binomial bino X X X X X X
Chi square chi2 X X X X X
Empirical e X
Extreme value ev X X X X X X X
Exponential exp X X X X X X X
F f X X X X X
Gamma gam X X X X X X X
Geometric geo X X X X X
Generalized extreme value gev X X X X X X
Generalized Pareto gp X X X X X X X
Hypergeometric hyge X X X X X
Lognormal logn X X X X X X
Multivariate normal mvn X X X
Multivariate t mvt X X X
Negative binomial nbin X X X X X X X
Noncentral F ncf X X X X X
Noncentral t nct X X X X X
Noncentral Chi-square ncx2 X X X X X
Normal (Gaussian) norm X X X X X X X
Poisson poiss X X X X X X
Rayleigh rayl X X X X X X
T t X X X X X
Discrete uniform unid X X X X X
Uniform unif X X X X X X
Weibull wbl X X X X X X X
Let’s do some examples in MATLAB. First, create a vector X with 1000 i.i.d. normal
random variables with zero mean and unit variance and then estimate its parameters.
>> X = normrnd(0,1,1000,1);
>> plot(X)
>> [mu,sigma] = normfit(X);
>> mu,sigma
mu =
-0.0431
sigma =
0.9435
Now, let’s find out how the PDF and CDF of certain distributions look like. First generate
the domain of the function with the command S = first:stepsize:end. For example, set the
interval (−5; 5) with a step of size 0.01 and find the PDF and CDF of a Student-t distribution
with 5, and 100 degrees of freedom:
>> Z = -5:0.01:5;Z=Z';
>> t5 pdf = tpdf(Z,5);t10 pdf = tpdf(Z,10);t100 pdf = tpdf(Z,100);
>> t5 cdf = tcdf(Z,5);t10 cdf = tcdf(Z,10);t100 cdf = tcdf(Z,100);
>> figure(1),plot(Z,[t5 pdf t100 pdf]),
>> figure(2),plot(Z,[t5 cdf t100 cdf]),
>> figure(3),plot(Z,[t5 pdf t5 cdf]),
>> figure(4),plot(Z,[t5 pdf cumsum(t5 pdf)*0.01]),
Introductory course in MATLAB Page 19
Note that Figures 3 and 4 above are pretty similar, as though they were plotting the same
functions. This happens because the CDF of a given value x is not more than the area below
the pdf up to this point, and this area can be easily approximated by the command cumsum.
This command simply replaces the ith element of a vector (in our case, the vector t5 pdf) by the
partial sum of all observations up to this element. Thus if D = [1 2 3 4], then cumsum(D) =
[1 3 6 10].
The Inverse CDF is pretty much used in hypothesis testing to find critical values of a given
known distribution. For example, consider testing the mean equal to zero in the vector X
created above. First, we construct the appropriate statistics, and then find the critical values
for α = 0.05 significance level. Since this is a two-tailed test, we should obtain the value that
leaves α/2 = 0.025 of probability in each tail.
Introductory course in MATLAB Page 20
Finally, let’s play a little more with the random number generators. We want to generate
time series of size T = 1000 with the following dynamic properties:
yt = yt−1 + at , (1)
xt = 3 + 0.5 at−1 + at , (2)
wt = −0.8 wt−1 + at + 0.5 at−1 , (3)
where at is an i.i.d. Gaussian process with zero mean and unit variance, commonly known as a
white noise process. Since all series depend on their own past values, we need to construct the
following loop to generate them:
From the plot we can see that the only series without a constant mean is yt , known as a
random walk process. Check that its first difference given by ∆yt = yt − yt−1 , is simply the
white noise process, at . The command to do this in MATLAB is diff(yt).
The Statistics toolbox provides functions for describing the features of a data sample. These
descriptive statistics include measures of location and spread, percentile estimates and functions
for dealing with data having missing values. The following table shows the most important ones
with a brief description of their use.
* Replace the particle stat by one of the following names: max, min, std,
mean, median, sum or var.
As an example, let’s find some sample statistics of the time series xt , wt and at generated
above. Before doing it, we must know that in a data matrix, MATLAB automatically interprets
columns as samples and rows as observations. Therefore, the output of all these functions
applied to the data matrix is a row vector with its ith element being the value of the statistics
for the ith column. Let’s now calculate the median, skewness, kurtosis, and the 25th and 75th
Percentile of the selected series by typing the following in the command window:
>> med = median([xt wt a]); % Calculating the median for each series
>> skew = skewness([xt wt a]); % Calculating the Skewness
>> kurt = kurtosis([xt wt a]); % Calculating the Kurtosis
>> prct25 = prctile([xt wt a],25); % Calculating the 25th Percentile
>> prct75 = prctile([xt wt a],75); % Calculating the 75th Percentile
>> med,skew,kurt,prct25,prct75,
>> med =
3.0026 -0.0438 -0.0001
>> skew =
-0.0854 0.0750 0.0311
>> kurt =
2.7254 2.8461 2.7629
>> prct25 =
2.2257 -0.7365 -0.6947
>> prct75 =
3.7530 0.7206 0.6734
Another way of obtaining the sample kurtosis or skewness is by using the command moment(x,n),
which finds the nth central sample moment of x. For example, knowing that the kurtosis is
defined as the ratio between the fourth central moment and the second central moment to the
squares, we could have done
The graphical methods of data analysis are as important as the descriptive statistics to collect
information from the data. In this section we will see some of these specialized plots available
in the Statistics toolbox and also others from MATLAB main toolbox. The Statistics tool-
box adds box plots, normal probability plots, Weibull probability plots, control charts, and
quantile-quantile plots to the arsenal of graphs in MATLAB. There is also extended support
for polynomial curve fitting and prediction. There are also functions to create scatter plots or
matrices of scatter plots for grouped data, and to identify points interactively on such plots. It
is true that the best way of plotting some data strongly depends on their own nature. Thus,
for instance, qualitative data information might be summarized in pie charts or bars, while
quantitative data in scatter plots. The table below shows some of the most known specialized
graphs.
Obviously, the histogram is the most popular in describing a sample. Let’s find out how to
use it. Consider the vector X of i.i.d. standard normal random variables, and the white noise
series, at . We will obtain the histogram for each variable and a 3-D version of the histogram
for both at the same time.
Introductory course in MATLAB Page 24
The histograms serve mainly for giving a first view of the shape of the distribution, and
thus infer whether the data come from a given known distribution. Moreover, they also serve
to detect outliers, as shown in the bottom-right figure above. This also shows the histogram
of X, but after adding two “large” (in absolute value) observations. It is clear that these two
outliers significantly change the shape of the histogram.
When dealing with discrete data, the stem function may be the appropriate graphic for
plotting them. For example, let’s generate data from a binomial distribution with parameters
p = 0.3 and n = 10. First, we need to obtain the frequency table that counts the number
observations for each value between 0 and 9. The right command is tabulate. Finally, the
Introductory course in MATLAB Page 25
commands stem and stairs produce the plots of the simple and cumulative frequencies given
by tabulate.
Finally, we will learn how to create the pie charts. Consider the following information about
the number of students of the Statistics Department that have started and finished the first-year
courses in the last four years:
In order to introduce this table in MATLAB and then plot its figure, we must follow these
steps:
Note that the vector of zeros and ones following the data input specifies whether to offset a
slice from the center of the pie chart; see the Help for further information.
Regression analysis is other big branch of Statistics covered by the Statistical toolbox. For
example, finding the Ordinary Least Squares (OLS) estimators of a given linear regression is
certainly easy in MATLAB. In fact, if we knew the algebra behind this procedure we could
use simple matrix algebra with the commands you have seen in previous sections. However,
the Statistics toolbox goes beyond that and provides much more information for inference and
testing with just a simple command named regress. In its simplest form, by typing B =
regress(Y,X) we find the OLS estimators of the linear regression of the dependent variable Y
on the regressors contained in matrix X. In other words, it estimates the vector β of the model
Y = X β + U, (4)
= β1 X1 + β X2 + ... + βp Xp + U,
Introductory course in MATLAB Page 27
where U is a vector of zero-mean random errors. If we further assume that U is Normal and X
is fixed (i.e. not random), then the OLS estimator, β̂OLS , is the best linear unbiased estimator
(BLUE) of the parameter β. Let’s see how the command regress works. First, we need to
enter some data to apply model (4). We will work with production costs of several factories that
produce steel. The data is located in a text-file called regress data.txt, which contains seven
variables with 129 observations. The variables are: price per unit, hourly salaries, energy costs,
raw material costs, machinery depreciation costs, other fixed costs and a discrete variable for
factory type (1=star, 0=neutral and 2=basic)2 . All variables except the binary one are in logs.
We wish to relate the unit price of steel with the different production costs by means of (4).
First, remember that to load the data we should type Data = load('regress data.txt'); on
the command window. Once the data have been loaded, it could be interesting to observe the
cloud of points in a scatter plot. Since there is a categorical discrete variable referring to the
geographical situation, we will use it to group the data into the three situations. Recall that
the command to do this is gplotmatrix (the simple scatter plot matrix is plotmatrix). The
command also allows to introduce the variable names and a histogram in the main diagonal, as
shown in the figure below. For more information about the usage of this function; see the Help.
2
This exercise is a modification of a practice of Statistics II. You will find all information here
Introductory course in MATLAB Page 28
The first row of the scatter plot provides a good insight that the linear model can be a good
alternative for relating these variables. Then, we finally estimate the parameter β of (4) and
the residual variance with the function regress. We first leave aside the categorical data. Note
also that we must add a vector of ones to the regressors matrix in order to include an intercept.
Note that in the residual plot, the zero-line is also drawn. To include it, we need fist to hold
on the current figure and then add the command line([x1 x2],[y1 y2]).
Optimization is the process of finding the minimum or maximum of a function, usually called the
objective function sometimes subject to constraints. The Optimization Toolbox consists of a set
of functions that perform minimization on general linear and nonlinear functions. The toolbox
Introductory course in MATLAB Page 29
also provides functions for solving nonlinear equation and least-squares (data-fitting) problems.
The Optimization toolbox includes routines for many types of optimization procedures like
• Linear programming
Given a mathematical function coded in an m-f ile, one can find a local minimizer of the function
in a given interval using an iterative algorithm called fminunc. It attempts to find a minimum
of a scalar function of several variables, starting at an initial estimate. Its syntax is as follows
>> [X,FVAL,EXITFLAG,OUTPUT,GRAD,HESSIAN] = fminunc('ObjFunction',X0,...
options,varargin)
Inputs:
• 'ObjFunction': is a function that accepts input X and returns a scalar function value
evaluated at X.
• X0: is a initial guess value for the iterative algorithm. It must be of the same size as X.
• options: is a structure containing all options about the way in which the algorithm is
searching the minimum point, e.g. the maximum number of iterations, gradient, hessian,
tolerance, among others. The following table summarizes the most common options.
Introductory course in MATLAB Page 30
FunValCheck 'off' | 'on' Check whether objective function values are valid.
'on'displays an error when the objective function
returns a value that is complex or NaN. 'off'
displays no error.
GradObj 'on' | 'off' Use the gradient provided by the user.
MaxFunEvals Positive integer Maximun number of objective function
evaluation allowed.
MaxIter Positive integer Maximun number of iterations allowed.
TolFun Positive scalar The minimum tolerance for the objective function.
TolX Positive scalar The minimum tolerance for the norm of parameters.
Hessian 'on' | 'off' Use the hessian provided by the user.
• varargin: are the additional input that could have the objective function (’ObjFunction’).
The number of Output may vary according to our need, and they can be:
• FVAL: is the value of the objective function at the optimal point, (X).
• EXITFLAG: is the value that describes the exit condition of the command fminunc reaching
the solution X. It can be: 1 magnitude of gradient smaller than the specified tolerance; 2
change in X smaller than the specified tolerance; 3 change in the objective function value
smaller than the specified tolerance (only occurs in the large-scale method); 0 maximum
number of function evaluations or iterations reached; -1 algorithm terminated by the
output function; -2 line search cannot find an acceptable point along the current search
direction (only occurs in the medium-scale method).
• OUTPUT: is a structure with: the number of iterations taken, the number of function
evaluations, the number of CG iterations (if used) in OUTPUT.cgiterations, the first-
order optimality (if used), and the exit message.
• GRAD: is the value of the gradient of the objective function at the solution X.
• HESSIAN: is the value of the Hessian of the objective function at the solution X.
Application: Consider, again, model (4). But now, we are going to minimize the sum
squares of the residuals numerically. We mean that first create a function in MATLAB that
Introductory course in MATLAB Page 31
returns the value of the sum squares of the residuals given a particular value of parameters and
the data, then, we use the command fminunc for finding a minimum. As we have seen, the
parameters can be estimated using the command regress.
Let OLS b be the function that returns the value of the sum squares of the residuals given
a particular value of the parameters and the data. Now, we enter
>> [par,fval,exitflag,output] = fminunc('OLS b',Ini Guess,[],X,y)
with [], we left the default options and we add the input X and y which are the additional
input of the OLS b function. The results will be
fval =
4.9923
exitflag =
3
output =
iterations: 40
funcCount: 41
stepsize: 1
firstorderopt: 1.8323e-005
algorithm: 'large-scale: trust-region Newton'
message: [1x86 char]
Now, we concern about finding an optimal point of a nonlinear function with several variables
but, in this case, we add linear and nonlinear, constraints. The problem is the following
minf (X)
X
s.t.
AX = b
C(X) = 0
Ain X ≤ bin
Cin (X) ≤ 0
lb ≤ X ≤ ub
A command for solving this type of problems is fmincon. It works in a similar way that
the command fminunc, but the command fmincon has more inputs, that refer to the constraints.
>> [X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN] = fmincon('ObjFunction',X0,...
Ain,bin,A,b,lb,ub,'NonConFunc',Options,Varargin)
Inputs:
• 'ObjFunction': is a function that accepts input X and returns a scalar function value F
evaluated at X.
• X0: is an initial guess value for the iterative algorithm, it can be a scalar, vector or matrix.
• Ain,bin: are the matrix and vector, respectively, that form, together with “X”, the linear
Introductory course in MATLAB Page 33
• A,b: are the matrix and vector, respectively, that form, together with “X”, the linear
equality constraints. (Set A=[] and b=[] if no equalities exist.)
• lb,ub: are the vector of lower bounds and the upper bounds, respectively, of the variables
“X”. (Set lb=[] and/or ub=[] if no bounds exist.)
• 'NonConFunc': is a function that accepts “X” as input and returns the vectors Cin (X)
and C(X), representing the nonlinear inequalities and equalities constraints, respectively.
• options: is a structure in which are all options about the way in which the algorithm is
looking for the minimum point, e.g. the maximum number of iterations, the gradient, the
hessian, the tolerances among others.
• varargin: are the additional input that could have the objective function.
The number of Output’s can vary according our need and they can be:
• FVAL: is the value of the objective function at the optimal points, (X).
• EXITFLAG: is value that describes the exit condition of the command fminunc reaching
the solution X’s values. It can be: Both medium- and large-scale: 1 First order optimality
conditions satisfied to the specified tolerance. 0 Maximum number of function evaluations
or iterations reached. -1 Optimization terminated by the output function. Large-scale
only: 2 Change in X less than the specified tolerance. 3 Change in the objective function
value less than the specified tolerance. Medium-scale only: 4 Magnitude of search direction
smaller than the specified tolerance and constraint violation less than options.TolCon.
5 Magnitude of directional derivative less than the specified tolerance and constraint
violation less than options.TolCon. -2 No feasible point found.
• OUTPUT: is a structure with five blocks of information. Namely, the number of itera-
tions taken, the number of function evaluations, the number of CG iterations (if used) in
OUTPUT.cgiterations, the first-order optimality (if used), and the exit message.
• LAMBDA: is the Lagrange multipliers at the solution X. LAMBDA.lower for lb, LAMBDA.upper
for ub, LAMBDA.ineqlin is for the linear inequalities, LAMBDA.eqlin is for the linear
equalities, LAMBDA.ineqnonlin is for the nonlinear inequalities, and LAMBDA.eqnonlin is
for the nonlinear equalities.
• GRAD: is the value of the gradient of the objective function at the solution X.
Introductory course in MATLAB Page 34
• HESSIAN: is the value of the Hessian of the objective function at the solution X.
Suppose that we have money to invest on two different assets. Asset1 has a mean return
r1 = 0.07 and a standard deviation σ1 = 3; while Asset2 has a mean return r1 = 0.3 and a
standard deviation σ2 = 5. The correlation between both assets is ρ = 0.1. In this virtual
economy we must invest the totality of our money. Given this information our problem reduces
to minimize the risk (σP ) of our portfolio given a particularly value of the return.
rP = w1 r1 + w2 r2 ,
where, w1 and w2 are the weights invested in Asset1 and Asset2 , respectively. Its risk
q
σP = w12 σ12 + w22 σ22 + 2w1 w2 σ1 σ1 ρ.
We are looking for the weights that make minimum the risk without the possibility of take loan.
Now, we find the optimal weights entering in the Command Window the following,
first the options
opt = optimset('Display','iter','GradObj','off',...
'Hessian','off','LargeScale','off');
After that
>> [optwieghts,fval,exitflag,output,lambda] = fmincon('risk',[0.1 0.1],...
[],[],[1 1],1,[0 0],[1 1],[],opt,sig1,sig2,ro)
The results will be
iterations: 5
funcCount: 18
lssteplength: 1
stepsize: 4.7398e-004
algorithm: 'medium-scale: SQP, Quasi-Newton, line-search'
firstorderopt: 1.3411e-006
message: [1x172 char]
lambda =
lower: [2x1 double]
upper: [2x1 double]
eqlin: -2.6806
eqnonlin: [0x1 double]
ineqlin: [0x1 double]
ineqnonlin: [0x1 double]
In this case, it is possible to borrow money, let assume that the interest rate at which we take
the loan is the same as Asset1 . For example, we can borrow money by means of selling Asset1
(“leverage”) and using it for buying Asset2 , this situation can be summarized as a negative
weight for Asset1 and a positive and greater than one weight for Asset2 (their sum must be
equal to one).
Now, our problem consists in minimizing the risk subject to the level of return being fixed,
Introductory course in MATLAB Page 37
e.g. r0 = 0.6.
q
min f (w1 , w2 ) = w12 σ12 + w22 σ22 + 2w1 w2 σ1 σ1 ρ
w1 ,w2
s.t.
w1 r1 + w2 r2 = 0.6
w1 + w2 = 1
Now, we find the optimal weights entering in the Command Window, first the options
opt = optimset('Display','iter','GradObj','off',...
'Hessian','off','LargeScale','off');
After that, we enter
>> [optwieghts,fval,exitflag,output,lambda] = fmincon('risk',[0.1 0.1],...
[],[],[r1 r2;1 1],[R0;1],[],[],[],opt,sig1,sig2,ro)
The results will be
3 Programming in MATLAB
MATLAB is a high-level language that includes matrix-based data structures, its own internal
data types, an extensive catalog of functions, an environment in which to develop our own
functions and scripts. MATLAB provides a full programming language that enables us to write
a series of MATLAB statements into a file and then execute them with a single command. we
write our program in an ordinary text file, giving the file a name of filename.m. The term we
use for filename becomes the new command that MATLAB associates with the program. The
file extension of .m makes this a MATLAB m-f ile. For example, when we write a program in
MATLAB, we save it to an m-f ile. There are two types of m-f iles: the scripts that simply
execute a sequence of MATLAB statements, and the functions that also accept input arguments
and produce outputs.
Introductory course in MATLAB Page 39
The simplest m-f iles are the Scripts. They are useful for automating blocks of MATLAB
commands, such as computations we have to perform repeatedly from the command line. Scripts
can operate on existing data in the workspace, or they can create new data on which to operate.
Although scripts do not return output arguments, they record all the created variables in the
workspace, so that we can use them in further computations. In addition, scripts can produce
graphical output using commands like plot.
Like any other m-f iles, scripts accept comments. Any text followed by a percent sign (%)
on a given line is a comment. Comments may appear on separate lines by themselves, or simply
at the end of an executable line.
For example, let’s create an m-f ile to construct the plot made in section 1. First, in “File”,
“New ”, click on “M-File”. This action opens a new window in which we can edit the m-f ile.
Next, inside this window we enter all the necessary commands.
clear % Clear all variables from memory
hold on
hold off
set(gr,'LineStyle','--','LineWidth',2.5, 'Color', 'r'); % Set the styles, color and width for the first plot
set(gr1,'LineStyle','-','LineWidth',2, 'Color','g'); % Set the styles, color and width for the second plot
ylabel(['sin(\theta),',sprintf('\n'),'cos(\theta)'],'Rotation',0.0,'FontWeight','bold','FontSize',11);
Introductory course in MATLAB Page 40
3.2 Functions
Function [out1, out2, ...] = funname(in1, in2, ...) defines the function funname that
accepts inputs in1, in2, etc. and returns outputs out1, out2, etc. The name of a function,
defined in the first line of the m-f ile, should be the same as the name of the file without the
“.m” extension. For example, we create a function with the weights, the standard deviations
associated to each assets and the correlation between each other as input and returns the risk,
measured as the standard deviation of the portfolio.
function [R Var] = risk(weights,sig1,sig2,ro)
% [R Var] = risk(weights,sig1,sig2,ro)
w1 = weights(1);
w2 = weights(2);
sig12 = sig1∧ 2;
sig22 = sig2∧ 2;
Now we leave you constructing your own m-f iles to solve some exercises we have prepared
specially for you!
1. A Chinese factory specialized in producing plastic dolls wishes to analyze some data on
exports to Spain. The database is given in a text file called chinese data.txt. At the end
of this tutorial you will find the whole database with all the information you need. It
contains information about the 2005 and 2006 sales of three different types of dolls, A, B
and C. In particular, the share-holders wish to know which is the type of doll with best
position at the Spanish market, and how these sales are spanned among the provinces.
As their head of the sales department, you need to summarize the information by
(a) Obtaining the main descriptive statistics, for each year and type of doll.
Introductory course in MATLAB Page 41
(b) Making different plots to have an intuition about the type of data we have and to
account for possible outliers.
(c) Testing whether the mean sales of each type are equal for a given year.
(d) Checking, for three provinces chosen at random, whether the sales of each type
have increased from 2005 to 2006. Then indicate in how many provinces the sales of
type B have been increased.
We encourage you to put all the statements in a script m-f ile and then run them all at
once to check the results. Don’t worry, we will help you on this!!
2. This Chinese factory is in fact part of a big holding of multinational firms. The CEOs of
this holding, after your excellent performance as the head of the sales department, offer
you a position at their financial department. But, of course, to get this job they ask
you to find the optimal portfolio composition of four different indexes, according to their
expected returns. In the file holding shares.txt you will find information about the daily
returns of these four different indexes in the last two months. In particular, you need to:
(a) Find the mean and the variance-covariance matrix of these returns.
(b) Use this information as inputs to minimize the risk of the portfolio (measured as its
standard deviation), subject to a fixed value of the portfolio return.
(c) Construct a loop to repeat the last minimization but with different portfolio returns.
(d) Plot the efficient frontier and compare it to the free risk return, rf = 0.01%