29
An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin University of Chicago Booth School of Business January 25, 2012 1

An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Embed Size (px)

Citation preview

Page 1: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

An Introduction to MATLABSee Chapter 1 of Gilat

Kipp MartinUniversity of Chicago

Booth School of Business

January 25, 2012

1

Page 2: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Outline

2

Page 3: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

The MATLAB IDE

MATLAB is an acronym for Matrix Laboratory. It was originally alinear algebra package. It has developed into an IntegratedDevelopment Environment (IDE). It consists of the following:

1. Desktop Tools – a set of tools such as a command window,text editor, file browser (similar to Windows explorer),command history window, GUI building tool, a tool forcreating and editing plots, and debugging tools.

2. Mathematical Function Library – a vast array of mathematicalfunctions that can be executed from the command line orfrom scripts

3. A Scripting Language

3

Page 4: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

The MATLAB IDE

MATLAB IDE (continued):

4. Graphics – MATLAB offers very powerful two and threedimensional graphics. There is also a tool for editing andcreating plots

5. API – you can write C, FORTRAN, and Java routines thatuse MATLAB functions and you can call C, FORTRAN, andJava routines from MATLAB

6. Numerous Toolboxes to extend functionality (more on this ina few slides)

4

Page 5: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

The MATLAB IDE

MATLAB is very powerful. Here are a few of the many things youcan do with MATLAB.

I You can use MATLAB as a calculator. It has a vast library offunctions you can use. If you need a function that is notincluded you can write it using the scripting language.

I MATLAB is an extremely powerful linear algebra tool. Youcan use MATLAB for inverse calculations, LU decomposition,Cholesky factorization, etc.

I You can use MATLAB for statistical analysis. There areroutines for calculating means, variances, correlations, runningregressions, forecasting models, etc.

I Do symbolic mathematics, for example symbolic integrationand differentiation.

I Use MATLAB for mathematical optimization.

5

Page 6: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

The MATLAB IDE

I Use MATLAB for simulation models.

I Use the extensive graphing features for two and threedimensional plots and histograms.

I Use the MATLAB scripting language to create your ownfunctions and programs.

I Use the MATLAB GUI tool to build user interfaces to models.

I Use MATLAB to call routines written in C, C++, FORTRAN,and Java. MATLAB has a very powerful API (ApplicationProgram Interface). You can also call MATLAB routines fromC and Java.

I MATLAB can import and export data in various formats.

I With MATLAB you can generate compiled applications thatdo not need MATLAB as a host.

6

Page 7: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

The MATLAB IDE

MATLAB out-of-the-box does not have all of the features justdescribed.

There are Toolboxes you must purchase to extend the basicfunctionality of MATLAB.

For example, the Booth PC Lab has the basic MATLAB Toolboxand several others (which seems to change).

There are numerous Toolboxes available. For example, there is aFinancial Derivatives Tool Box, a Fixed-Income Toolbox, etc. Seehttp://www.mathworks.com/products/product_listing/index.html.

7

Page 8: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

The MATLAB IDE

There are a number of competing products.

I Similar comprehensive products include Mathematica andMaple

I Competitors in the area of statistics include SAS, R, S, andGAUSS.

I Excel with VBA is a competitor

I There are also programming language IDE’s such as Eclipseand Visual Studio .NET

8

Page 9: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

The Command Window/Tool

MATLAB provides a command window/tool. This is the “controlcenter.” When MATLAB opens it puts you in the commandwindow.

Command Resultclc clear the command windowclear clear the variables and functions from memorypwd print the current directoryls list all of the files in the current directoryedit invoke the editorplottools invoke the GUI for making plotscd .. move up one directorycd path to directory cd to the specified directorypath list all of the paths that MATLAB looks forhelpdesk bring up the MATLAB help systemedit bring up the editor

9

Page 10: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

The Command Window/Tool

It is also possible to execute DOS or Unix commands from theMATLAB command window. To do so, put an ! before thecommand. For example

!del filename

The command window has command completion – use TAB key.

Control Key Sequence OperationCtrl+P Recall the previous commandCtrl+N Recall the next lineCtrl+B Move back one characterCtrl+F Move forward one characterCtrl+A Move to beginning of command lineCtrl+E Move to the end of the command lineCtrl+Home Move to top of command windowCtrl+End Move to end of command windowCtrl+U Clear command line

10

Page 11: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Path, Directories, and File Explorer

In order for MATLAB to execute these functions and programsthey must be on path searched by MATLAB. To see which pathsMATLAB searches type in path at the command line. To add anew path do either of the following

>> addpath(‘path to file’)

You can also add a path using the GUI. Select Set Path in theFile menu.

Don’t forget to click Save so it will remember the path for futuresessions.

Also, you may wish to use the option Add With Subfolders.

11

Page 12: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Path, Directories, and File Explorer

Use the cd command to connect to the desired directory. Forexample,

>> cd c:\b36104\matlab

If there are embedded blanks in the path but the path in singlequotes. For example

>> cd ‘c:\Documents and Settings’

To move up one directory type

>> cd ..

12

Page 13: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Path, Directories, and File Explorer

In order to list the files in the current directory type in ls. Inorder to see the current working directory type in pwd.

MATLAB comes with a file explorer that is very similar to whatyou have in Windows. You can:

I navigate through directories

I create new directories

I delete files and directories

13

Page 14: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

The MATLAB Editor

MATLAB also has a text editor. You will use this text editor tocreate your own programs and functions. There are two ways toinvoke the text editor.

You can invoke the text editor from the command line with edit.

You can also go to the File menu item, select New, and then MFile.

The MATLAB editor is a plain-text editor, not a WYSIWYG editorsuch as Microsoft Word (thank goodness!!!!).

14

Page 15: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

MATLAB as a Calculator

Matlab can be used as a calculator. Type in any arithmeticexpression to get the result.

>> 1+10^2/50*10ans = 21

Here is a list of the basic MATLAB operators for arithmetic.

Symbol Operation Example

+ Addition 2 + 2 = 4− Subtraction 2 - 3 = -1∗ Multiplication 2*5 = 10/ Right Division 4/2 = 2\ Left Division 4\2 = 2/4 = .5∧ Power or exponentiation 23 = 8

15

Page 16: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

MATLAB as a CalculatorMATLAB follows the standard precedence rules when evaluatingarithmetic expression using infix notation. Multiplication anddivision have higher precedence than addition and subtraction

>> 5+4*3+1ans = 18

When there is a tie among operators with the same precedence wefollow the left associative rule.

>> 35/7/5*1ans = 1

Exponentiation has higher precedence than multiplication anddivision.

>> 100-3*5^2ans = 25

16

Page 17: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

MATLAB as a Calculator

Exponentiation is right associative.

2/2^1^3

Should behave like

2/(2^(1^3))

and evaluate to 1. However, both MATLAB and Excel violate thistime-held tradition and use left associativity to evaluateexponentiation. That is, in MATLAB (and Excel)

>> 2/2^1^3ans = 0.2500

17

Page 18: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

MATLAB as a Calculator

Now, what about unary minus? In MATLAB,

>> -1^2ans = -1

However, in Excel −12 = 1. When ever I write an equation assumethat unary minus has low precedence, that is, we follow theMATLAB convention (which is the more common) in written work.

Finally, parenthesis always have the highest precedence. You arenever wrong to indicate the order of operations by usingparenthesis.

18

Page 19: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

MATLAB as a Calculator

Summary for arithmetic:

Table: Precedence order for arithmetic

parenthesisexponentiation left associativemultiplication, division left associativeaddition, subtraction left associative

19

Page 20: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Variables and Functions

MATLAB does not have strong typing of variables. In other words,you do not need to define the variable type as an integer, string,matrix, etc. You just write something such as

>> x = 34.76

>> y = ‘Mary Smith’

>> z = [1.2 3; 4, 9]

In the first case x is a real number, in the second case y is a stringvariable, in the third case z is a 2 by 2 matrix.

20

Page 21: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Variables and Functions

The following rules apply to naming variables.

I Variable names can contain letters, digits, and the underscorecharacter (no other characters).

I Variable names must start with a letter.

I Variable names can have up to 63 characters in MATLAB 7and above and 31 characters in MATLAB 6.

I MATLAB is case sensitive (Excel is not), X and x are distinctvariables.

I Do not create variable names that will conflict with built-infunction names, for example, do not define a variable sin.

21

Page 22: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Variables and Functions

Type in whos to get a list of all variables, their type, and theirdimension. (Type who is you just want a list of variables.)

>> whosName Size Bytes Classx 1x1 8 doubley 1x10 20 charz 2x2 32 double

MATLAB also has a phenomenal number of functions, bothelementary and specialized. Type in help elfun for elementaryfunctions and help specfun for more specialized and advancedfunctions.

A MATLAB expression is any combination of numbers, variables,functions, and operators.

22

Page 23: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Variables and FunctionsExample expressions:

>> x = 50;>> y = 73;>> x + sqrt(y)*5ans = 92.7200

Note: if you end an expression with a semicolon (;) MATLAB willnot write out the value of the expression. If you wish to continuean expression from one line to the next use ...

>> 5 + 34 ...+ 65ans = 104

Typing in the command clear will clear all functions and variablefrom memory. Typing in clear x will clear the variable x frommemory. Tying in clear y* will clear all variables starting withthe letter y .It is also possible to control the formatting of your numbers. Typein help format to see your options.23

Page 24: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

M Files

You can store a sequence of commands and expressions.

Open up the MATLAB editor (edit) and type in the commandsand expressions you wish to store. Then save the file. You willnotice that the file has a .m extension by default. These are callM-files.

If you save the file in a path that is searched by MATLAB, you canexecute the commands in the file by typing in the file name at thecommand line.

You must begin the name of an M-file with a letter from thealphabet.

24

Page 25: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

MAT Files

MAT files are binary files that store the variables in yourworkspace. For example, if you type in

>> x = 5;>> save xfile.mat

Quit MATLAB and then open it again. Then:

>> load xfile.mat>> whos

Name Size Bytes Class Attributes

x 1x1 8 double

25

Page 26: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

MAT Versus M Files

MAT files are binary files that store the variables in your workspace.

M Files are text files designed to store a sequence of commands, aprogram, or a function. More on functions and programs later.

If you do the following:

prices = load(’ASWch8ex13stockprices.txt’)save test

MATLAB will store the prices matrix. However, if you closeMATLAB, change the numbers in ASWch8ex13stockprices.txtand then

load test

it will have the old numbers.

26

Page 27: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Help

Table: MATLAB Help

Help Command Resulthelpdesk get entire MATLAB documentationhelp elfun a list of MATLAB elementary functionshelp specfun a list of more advanced MATLAB functionshelp elmat elementary matrices and matrix manipulationhelp matfun linear algebra and matrix functionshelp iofun input and output functionshelp “function name” help for the given functionhelp helptools a list of available help toolshelp general a list of general purpose commandshelp a list of all help topics

If you want to look for a command type in lookfor and then akeyword. For example lookfor variance.

27

Page 28: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Miscellaneous

You can change MATLAB’s default directory by creating a filestartup.m and putting it in the default startup directory of theMATLAB application.

For example, my startup.m file is

cd /Users/kmartin/Documents/files/coursework/36104-2011/matlab

In Windows (only) you can also set the startup directory by rightclicking on the MATLAB icon and selecting properties. In theStart in: tab, type in the default directory that you want.

28

Page 29: An Introduction to MATLAB See Chapter 1 of Gilatfaculty.chicagobooth.edu/kipp.martin/root/htmls/coursework/36104/... · An Introduction to MATLAB See Chapter 1 of Gilat Kipp Martin

Miscellaneous

If you want to keep track of all the commands and the result(which saving as a MAT file will not do) use the diary command.

diary logfeb15_2011.txt

This will record everything in file logfeb15 2011.txt. Use diaryoff to turn off the recording and diary on to turn it back on.

29