You are on page 1of 36

Introduction to Matlab

Lecture 1: Getting Started

Dr. Jack Favilukis (A313)


http://pages.stern.nyu.edu/~jfaviluk/teaching.html
Office Hours: Wed 14:30-15:30; Thu 16:30-17:30
What is Matlab?
• “The Language of Technological
Computing”
• A very fancy calculator
• A simple and user friendly
programming language
• A tool for data analysis and statistics
• A tool to produce plots
Accessing Matlab
Basics
• From LSE library:
Start/Programs/Teaching/Matlab R2007a
• If can’t find it, try searching for matlab.exe
• Great online tutorial:
http://web.mit.edu/olh/Matlab/Matlab.html
• Company Website: http://www.mathworks.com/
Course Outline

• Introduction to Matlab
• Simulation
• Portfolio Analysis
• Statistics and Time Series
• Fixed Income
• Options

Only by practicing what you see in


class will you get comfortable with
Matlab!!!
.m files

• .m files are just


text files
• Do work in .m file
• Paste work into
Matlab prompt
• Use ; to end lines
• Save .m files
• Use % to add comments
The Matlab Prompt

• >> denotes where you type commands


• Type or paste commands, then hit enter
• If entering multiple commands, separate them by ;
• Multiple commands may be on same line, as long as they
are separated by ;
• Ending a command with ; also tells matlab to not display
the output
• If want output displayed, do not use ;
• >>2+2
ans =
4
>>
Variables

• Variables are the basic building blocks


• Capitalization matters, x not same as X
• Matrix is a variable that contains multiple
entries, i.e. V=[.98 1.02 .99 1.07];
• Matlab is great with vectors and matrices,
however, their orientation and size matter
• You will get errors if try to add vectors of
different size or different orientation
Basic Operations

• Always use brackets [ ] to define matrices


• Always use prentices ( ) to call values of
matrices
• The row is always first, the column is
always second, i.e. M1(3,2) is not the
same as M1(2,3)
• To see which variables exist, use >>whos
• To delete variables, use >>clear x y
• To find out size use >>size(M1)
Elementary Algebra

• Use +, -, *, / for basic operations


• Use ./ and .* for element by element
operations on matrices and vectors
• Use / and * for matrix multiplication, but this
only makes sense if you’ve taken Linear
Algebra
• Use ‘ to transpose a matrix
• You can always multiply a matrix by a
scalar
• You can always overwrite old variables
Ranges of numbers

• Colon specifies range of numbers


• >>V3=[1:5] sets V3 to be the numbers 1
through 5
• >>V3=[1:3:13]’ sets V3 to be the numbers 1
through 13, skipping every 3rd, note, it is
transposed
• >>M5=M1(1:2,1:5) sets M5 to be all the
numbers in rows 1-2 and columns 1-5 of M1
• >>V3=M1(:,2) sets V3 to be the whole
second column of M1
Finding Data: Yahoo

• Go to finance.yahoo.com
• Enter a quote and hit get quotes
• Click on historical prices
• Enter a date range, scroll to bottom and click
Download To Spreadsheet
• Open spreadsheet in Excel
• Problem: dates come out weird if load into
Matlab
• Problem: this gives prices, usually need to
convert them to returns
Finding Data: WRDS

• Go to wrds.wharton.upenn.edu/connect
• Select dataset (i.e. CRSP)
• Select series (i.e. daily stocks)
• Select company name (i.e. VLCM) and
which info you want (i.e. prices and holding
period return)
• Click submit request and wait a moment
• Open the text file
• CRSP has historical stock and bond data,
COMPUSTAT has accounting data
CRSP output
Loading Data

• Open new .m file


• Type dataset=[ ];
• Copy all of the data from your Excel or text file and
paste it inside [ ]
• Save the .m file in Matlab’s work directory (this
should be the default directory), for example call it
matlabin.m
• At the Matlab prompt type: matlabin;
• This executes any code in the file matlabin.m
• Inside matlabin.m you have defined a matrix called
dataset, this matrix now exists in Matlab’s memory
just like any other matrix.
Potential Problems

• All rows must have same size!!!!!!!!


• Matlab only knows numbers, it will give you errors if
there are any letters in what you pasted!!!!!!!
• Do not include field headings in your copy/paste
• Date formats (i.e. 28-Dec-1979) may be
problematic. If pasting from Excel, I suggest not
pasting dates, or formatting them to numbers.
• Don’t forget semicolon, otherwise all data will
appear on screen
• This procedure may crash your computer if dataset
is too big (50000 numbers should be no problem)
Writing Data

• Matlab can write any variable to a text file


• >>dlmwrite(‘filename.txt’, X, ’ ’);
• You can then open this text file manually,
or have Excel open it
• If open in notepad, sometimes line breaks
look weird. Just open it in something else,
like Word or Wordpad
• dlmread exisits but I don’t use it
Useful functions
More functions

• >>var(dataset(:,4)) %variance
• >>cov(dataset(:,4),bp(:,4)) %similar to corrcoef but
gives the variance and covariance
• >>sum(dataset(:,4)) %adds up all numbers in the
4th row of dataset
• >>abs(x) %absolute value
• >>x.^3 %takes powers (note, . only needed for
element by element)
• >>exp(x) %exponent
• >>sqrt(x) %square root
• >>round(x) %rounds to nearest integer
Plots
• >>[a b]=size(dataset); t=1:a;
• >>plot(t,dataset(:,4),’b’);
Plots
• >>hold on;
• >>plot(t,bp(:,4),’r--’);
Multiple plots
• >>hold off;
• >>subplot(2,1,1);
• >>plot(t,dataset(:,3),’b’);
• >>subplot(2,1,2);
• >>plot(dataset(:,4),bp(:,4),’k.’);
Labels
• >>xlabel(‘Volcom’);
• >>ylabel(‘British Petroleum’);
• >>title(‘Scatter Plot’);
Saving your work
• >>save workspace1 x y % saves the
variables x and y in a file called
workspace1.mat
• >>save workspace1 % saves all variables
in workspace1.mat
• >>load workspace1 % loads the variables
in workspace1.mat
• >>clear all % deletes all variables
Getting help
• >>help %lists topic areas, for example one
of these is graph2d
• >>help graph2d %lists functions within
graph2d, for example plot
• >>help plot %gives help on plot
• >>lookfor keyword %searches for
keywords within help, pretty slow
Next week
• Logic
• Loops
• Creating your own functions
Functions we learned

• General: whos, clear, size, dlmwrite, save


• Matrix: zeros, ones, whos
• Math: +, -, *, /, ^,sum, exp, abs, sqrt, round
• Stats: min, max, mean, std, corrcoef, var,
cov
• Plots: plot, hold, subplot, xlabel, ylabel, title

You might also like