Introduction to MATLAB
Joao Pedro Pereira, 9/Oct/2014
1 Basic setup
- Command window
- Current directory
o Default: C:\MATLAB7\work
o To change it: drop-down menu or cd 'C:\[...path...]\myfolder'
2 Data Structures
- Simple variables:
o A = 5
o a = 10*3^(5-2)
o Warning: Matlab is case sensitive!!
- Matrix:
o A = [110 120; 210 220]
o To get the values stored in the matrix use subscripts:
A(1,2)
A(1,:)
- Multidimensional arrays, strings, structures (see tutorial)
3 Matrix operators
- Standard rules: A + B , A – B , A * B
- Element-wise operations: A .* B , A ./ B
- Transpose and inverse: A’ , inv(A)
4 Built-in functions
- Ex: exp(5) , log(10)
- Ex: sum(A) , mean(A) , std(A)
- Easy way to create some useful matrices:
o ones(5,1)
o eye(5)
o zeros(3,2)
- Generate random numbers from standard normal distribution:
o randn(5,1)
- The help system is very good – just type the name of what you need to do.
5 Scripts & User created Functions (.m files)
Script:
clear; clc;
a = 2;
b = 3*2;
c = a + b
Page 1 of 5
Function:
Write the following in a separate .m file and save it as add2num.m.
function out = add2num(in1,in2)
out = in1 + in2;
Can use this function in any other script or function by doing:
y = add2num(a,b)
6 Toolboxes
- Some come with matlab. Important toolboxes: optimization, statistics.
- Public domain:
o www.mathworks.com has many functions posted by users
o http://www.spatial-econometrics.com/ is a useful toolbox for
econometrics
o Search with Google…
- Functions written in C or Fortran can be compiled and integrated into Matlab
Note: need to update the path after installation of new toolboxes.
7 Plots
7.1 Simple x-y plot
c = 0.5:0.1:1.5;
u = log(c);
plot(c,u);
7.2 Figures with several plots
figure(1)
% draw density
subplot(2,1,1);
x = (-5:0.01:5)';
y = normpdf(x,0,1);
plot(x,y)
% generate random numbers and plot histogram
subplot(2,1,2);
z = randn(10000,1);
hist(z,50)
8 Input data from Excel
Excel file named datafile.xls
y x1 x2
10 2 1000
20 5 1500
30 4 940
25 1 700
15 6 500
16 9 1900
Page 2 of 5
Script:
N = xlsread('datafile.xls');
y = N(:,1);
X = N(:,2:3);
% do a linear regression:
beta = inv(X'*X)*X'*y
9 To save your output
Ouput as Figure: save it as jpg or eps using the figure menu; then import into
Word, Latex, etc.
Output in Command window: copy-paste.
Data created in Matlab
o Save it in a .mat file: save filename.mat var1 var2 (or use the
buttons in the workspace window)
o Retrieve the data with: load filename.mat
o Can also export data in Excel, txt, csv formats (search help)
10 Programming
10.1 Example: for cycle, if statement
% remove outliers
prices = [23 25 2000 22 21]'
[T ~] = size(prices);
for t = 1:T
if prices(t) > 1000
prices(t) = NaN;
end
end
10.2 Example: portfolio choice
(These are the initial steps of the homework project)
10.2.1 Main script
% HW on the mean-var frontier
clear; clc;
% input data
temp = xlsread('10_Industry_Portfolios');
ret = temp(:,2:end)/100;
rf = 0.4/100;
% compute moments
er = (mean(ret))';
V = cov(ret);
% draw the frontier
reqrets = 0.00:0.001:0.02;
for i = 1:length(reqrets)
[trash, rfront(i), varfront(i)] = frontierp(reqrets(i),V,er);
end
Page 3 of 5
figure(1);
plot(varfront.^.5,rfront);
title('Mean-Std Frontier');
ylabel('E[ret]'); xlabel('\sigma(ret)');
% now add frontier with rf
for i = 1:length(reqrets)
[trash, rfront(i), varfront(i)] =
rffrontierp(reqrets(i),V,er,+rf);
end
hold on;
plot(varfront.^.5,rfront);
hold off;
10.2.2 Auxiliary function
function [weights, retp, varp] = frontierp(E,V,er)
%
% E required ret on the porf
% V cov matrix
% er vector of expected returns
T = length(er);
% Mean var frontier
one = ones(T,1); % unit vector
A = one'*inv(V)*er;
B = er'*inv(V)*er;
C = one'*inv(V)*one;
D = B*C - A^2;
weights = (C*E-A)/D* inv(V)*er + (B-A*E)/D*inv(V)*one;
retp = weights'*er;
varp = weights'*V*weights;
10.2.3 What is left for you to do?
1) Write the auxiliary function rffrontierp() in a new rffrontierp.m file.
2) Complete the main script to answer the other questions in the homework.
10.3 Example: optimization
Example: find the minimum of f(x) = x^2 – 3.
Auxiliary function (in file myfn.m):
function y = myfn(x)
y = x^2 - 3;
In the main script:
x0 = 5; % initial guess
[xopt, fopt] = fminsearch(@myfn,x0)
Page 4 of 5
The Optimization toolbox has several functions for other optimization problems
(constrained, etc)
10.4 Debugger
Matlab has an excellent debugger. If your code has an error or is not giving the expected
result, using the debugger is the best way to fix the code.
1. In the Editor, click the “-“ next to the line number(s) you want to audit. A red dot
will appear.
2. Run the code (F5)
3. Matlab will pause on the line you marked and allow you to see all the current
variables.
4. Click on the buttons or press F5 to continue to the next lines.
11 Where to go from here
- Good tutorial at Help\Matlab\Getting Started
- Search full text or for function names in the Help search box
- If you are totally new to programming, a good place to start is http://code.org/
Page 5 of 5