This action might not be possible to undo. Are you sure you want to continue?

BooksAudiobooksComicsSheet Music### Categories

### Categories

### Categories

### Publishers

Scribd Selects Books

Hand-picked favorites from

our editors

our editors

Scribd Selects Audiobooks

Hand-picked favorites from

our editors

our editors

Scribd Selects Comics

Hand-picked favorites from

our editors

our editors

Scribd Selects Sheet Music

Hand-picked favorites from

our editors

our editors

Top Books

What's trending, bestsellers,

award-winners & more

award-winners & more

Top Audiobooks

What's trending, bestsellers,

award-winners & more

award-winners & more

Top Comics

What's trending, bestsellers,

award-winners & more

award-winners & more

Top Sheet Music

What's trending, bestsellers,

award-winners & more

award-winners & more

P. 1

MATLAB_Introduction_2009|Views: 125|Likes: 5

Published by monitim

See more

See less

https://www.scribd.com/doc/47939229/MATLAB-Introduction-2009

12/15/2012

text

original

- IntroductiontoMATLAB
- 1.1 TheInterface
- 1.2 TheEditor
- 1.3 Help
- 1.4 Demos
- 1.5 Exercises
- BasicInput
- 2.1 VariableNames
- 2.2 EnteringVectors
- 2.3 EnteringMatrices
- 2.4 HigherDimensionArrays
- 2.6 Concatenation
- 2.8 CallingFunctions
- 2.9 Exercises
- ImportingandExportingData
- 3.1 ImportingData
- 3.2 RobustDataImporting
- 3.5 Text
- 3.9 StatTransfer
- 3.10 ExportingData
- 3.11 Exercises
- BasicMath
- 4.1 Operators
- 4.3 MatrixMultiplication(*)
- 4.6 MatrixExponentiation(∧)
- 4.7 Parentheses
- 4.8 . (dot)operator
- 4.9 Transpose
- 4.10 OperatorPrecedence
- 4.11 Exercises
- BasicFunctions
- 5.1 Exercises
- SpecialMatrices
- 6.1 Exercises
- MatrixFunctions
- 7.1 MatrixManipulation
- 7.2 LinearAlgebraFunctions
- Inf,NaNandNumericLimits
- 8.1 Exercises
- LogicalOperatorsandFind
- 9.3 logical
- 9.4 allandany
- 9.5 find
- 9.6 is*
- 9.7 Exercises
- FlowControl
- 10.1 if...elseif...else
- 10.2 switch...case...otherwise
- 10.3 Exercises
- 11.1 for
- 11.2 while
- 11.3 break
- 11.4 continue
- 11.5 Exercises
- 12.1 SupportFunctions
- 12.2 plot
- 12.3 plot3
- 12.4 scatter
- 12.5 surf
- 12.6 mesh
- 12.7 contour
- 12.8 subplot
- 12.9 AdvancedGraphics
- 12.10 Exercises
- ExportingPlots
- 13.1 print
- 13.2 Exercises
- CustomFunctions
- 14.1 Comments
- 14.2 Debugging
- 14.3 Exercises
- ProbabilityandStatisticsFunctions
- 15.1 quantile
- 15.2 prctile
- 15.3 regress
- 15.5 TheUCSD_GARCH/MFEToolbox
- 15.7 Exercises
- 16.1 fminunc
- 16.2 fminsearch
- 16.3 fminbnd
- 16.4 fmincon
- 16.5 optimset
- 16.6 OtherOptimizationRoutines
- 17.1 datenum
- 17.2 datestr
- 17.3 datevec
- 17.4 nowandclock
- 17.5 ticandtoc
- 17.6 etime
- 17.7 datetick
- StringManipulation
- 18.1 Exercises
- StructuresandCellArrays
- 19.1 Structures
- 19.2 CellArrays
- FileSystemandNavigation
- 20.4 Exercises
- PerformanceandCodeOptimization
- 21.1 Pre-allocateDataArrays
- 21.5 UseM-Lint
- SimulationandRandomNumberGeneration
- 22.2 ReplicatingSimulationData
- QuickFunctionReference
- 23.1 GeneralMath
- 23.2 Rounding
- 23.3 Statistics
- 23.4 RandomNumbers
- 23.5 Logical
- 23.6 SpecialValues
- 23.7 SpecialMatrices
- 23.9 MatrixManipulation
- 23.10 SetFunctions
- 23.11 FlowControl
- 23.12 Looping
- 23.13 Optimization
- 23.14 Graphics
- 23.15 DateFunctions
- 23.16 StringFunction
- 23.17 TrigonometricFunctions
- 23.18 FileSystem
- 23.19 MATLABSpeciﬁc
- 23.20 Input/Output

Kevin Sheppard University of Oxford September 29, 2009

2

c 2005-2009 Kevin Sheppard

Contents

1 Introduction to MATLAB 1.1 The Interface . . . 1.2 The Editor . . . . . 1.3 Help . . . . . . . . 1.4 Demos . . . . . . . 1.5 Exercises . . . . . 9 9 10 12 13 13 15 15 16 16 17 17 17 18 20 21 23 23 23 24 27 28 28 28 30 31 31 31 33 33 33

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

2

Basic Input 2.1 Variable Names . . . . . . . . . 2.2 Entering Vectors . . . . . . . . 2.3 Entering Matrices . . . . . . . . 2.4 Higher Dimension Arrays . . . 2.5 Empty Matrices ([]) . . . . . . 2.6 Concatenation . . . . . . . . . 2.7 Accessing Elements of Matrices 2.8 Calling Functions . . . . . . . . 2.9 Exercises . . . . . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

3

Importing and Exporting Data 3.1 Importing Data . . . . . . . . . . . . . . . . . . 3.2 Robust Data Importing . . . . . . . . . . . . . . 3.3 Reading Excel Files . . . . . . . . . . . . . . . . 3.4 CSV Data . . . . . . . . . . . . . . . . . . . . . 3.5 Text . . . . . . . . . . . . . . . . . . . . . . . . 3.6 MATLAB Data Files (.mat) . . . . . . . . . . . . 3.7 Manually Reading Poorly Formatted Text . . . . 3.8 Reading Poorly Formatted Text Using textscan 3.9 Stat Transfer . . . . . . . . . . . . . . . . . . . . 3.10 Exporting Data . . . . . . . . . . . . . . . . . . 3.11 Exercises . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

4

Basic Math 4.1 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 Matrix Addition (+) and Subtraction (-) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.8 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Matrix Manipulation . . . . . . . . >=. . . . . . . . .4 continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & (AND). . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11. . . . . . . . . . . . . . . . 65 67 68 69 69 . . . . . . . . . . . 11. . . . . . . . . Matrix Exponentiation (∧ ) . . . . . . . . . . . . . . . . . <. . . . . <=. .3 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 4. . . . . . . . . . . . . . . . . . . . . . . . . is* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exercises 10 Flow Control 10. . . . . . . .5 Exercises . . . all and any . . . . . . .1 9. . . . . . . . . . . . . Logical Operators and Find 9. .9 Matrix Multiplication (*) . . else . . .6 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .case. Matrix Right Divide (\) . . .7 >. . . . . . . . . . . . . . . . . . . . . . . . . . 45 47 Special Matrices 6. . .1 7. 11. . . . . . . . . . . . . . . . .3 9. . . . . . . . . . . . . . . . . . . . 11. . . find . . . . . . . . Matrix Division (/) . . . . . . . . . . . . . . . . .1 for . . . . . 47 49 49 51 53 54 55 55 56 56 57 58 58 59 61 61 62 64 65 7 Matrix Functions 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 while . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 6 Exercises . . . . . . . . . . . . . . . . . . . . . . . (dot) operator . . . . . . . . . . . . . . . .4 9. . . . Parentheses . . . . . . . . . . . 8 Inf. . . Linear Algebra Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | (OR) and ∼ (NOT) . . . . . . . 34 34 34 35 35 35 36 36 36 37 4. . . . . . . . . . 4. . . . .6 4. . . . . . . . . . . . . . . . . . . . logical .2 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 CONTENTS 4. . .otherwise . . . .5 9. . . .1 9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . ∼= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 4. . . . . .3 Exercises 11 Loops 11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . NaN and Numeric Limits 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11 Exercises 5 Basic Functions 5. . . . . . . . . . . . . . . . . . == . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 break . . . . . . . . . . . . . . . . . . . . . elseif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 4. . . . . . . . . . . . . . . . . . Transpose . . . . . . . . . . . . . . . . 10. . . . . . . . . . . . . . . . . . . . . . . . . . 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 switch.

. . . . . .1 fminunc . . . . . . . . . . . . . . . . 14. . .6 mesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Probability and Statistics Functions 15. . . . . 15. . . . . . . . . . . . . . . . . . . 12. . . . . 16 Optimization 16. . . . . . . . . . . . . .7 Exercises . . . . . . . . . . . . . . .6 The JPL Toolbox . . . . . 16. . . . . . . . . . . . . . 104 .5 optimset . . . . .1 Support Functions 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 fminsearch . . . . . . . . . . . . . . . . . . . . . . . . . . .2 plot . . . . . . . . . . . 16. . . 15. . . . . . . . . . . . 12. . . . .7 contour . . . . . . . . . . . .5 surf . .4 fmincon . . . . . . . . . . . . . . . . . . . . . . 100 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 fminbnd . . . . 104 105 105 106 107 108 108 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 scatter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16. . . . . .1 quantile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. . . . . . . . . . . . . . . . . .8 subplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. . . . . .CONTENTS 5 12 Graphics 12. . 16. . . . . . . . . . . . . . . . . .1 datenum . . . . . . .3 plot3 . . . . . . . . . . . . . . . .4 now and clock 17. . . . . . . . . . . . . . . . . . . . . . . . .3 Exercises . *inv . . . . . . . . . . . 16. . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 The UCSD_GARCH/MFE Toolbox 15. . . .1 print . . . . . . . . . . . . . . . . 14. . . . .5 tic and toc . . . . . . . . . . .2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 15. . . . . . . . . . . . . . . . . . . .3 regress . . *rnd. . . . . . . . . . . . . . . . . .2 datestr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Comments . . . . . . 15. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. . . . . . . . . . . . *pdf. . . . . . . . . . . . 17. 14 Custom Functions 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 *cdf. . . . . . . 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10 Exercises . . . . .9 Advanced Graphics 12. . . . . . . . . . . .3 datevec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13. . . . . . . . . . . . . . . . . 98 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 prctile . . . . . . . . . . . . . . . . . . . .6 Other Optimization Routines 17 Dates and Times 17. . . . . . . . . . . . . . . . . . . . . 71 71 71 73 75 76 78 79 79 80 83 85 87 89 91 92 93 94 95 95 95 95 95 96 96 96 13 Exporting Plots 13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 . . . . . . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . . . 99 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. . . . . . . . . . . . . . . . . . . . 15.

. . . . . . . . . . . . . . .6 Special Values . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Avoid Operations that Require Allocating New Memory 21. .1 Pre-allocate Data Arrays . . 19. . . . . . . . . . . . . . 23. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Proﬁle Code to Find Hot-Spots . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Core Random Number Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 Matrix Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 etime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Using a Custom Path in a Shared Environment 20. . . . . . . . . . . . . . . . . . . . . . . .2 Rounding . 23. . . . . . . . . . . .2 Cell Arrays . . . . . .2 The MATLAB Path . . . . . . . . . . . . . . . .1 Structures . . . . . . . . . .3 Considerations when Running Simulations on Multiple Computers . . . . . . . .3 Use Vector and Matrix Operations . . . . 21. . 22 Simulation and Random Number Generation 131 22. .6 CONTENTS 17. . .4 Use Pre-computed Values in Optimization Targets . . . . . . . . 20 File System and Navigation 20. . . . . . . .1 Addressing the File System Programmatically 20. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 The Problem with Structures . . . 108 17. . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . 133 133 134 135 136 137 138 138 139 140 140 141 . . . . . . . . . . . . . . . . . . 108 18 String Manipulation 111 18. . . . . . . . . . . . . . . . . . . . . 132 23 Quick Function Reference 23. . . . . . . . . 23. . . . . . . . . . .3 Accessing Elements of Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 22. . . . . .7 datetick . . . . . . . . . . . 23. . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . 19. 23. . 23. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10 Set Functions .4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Logical . . . . . . . . . . . . . . . . . . . . . . . . . . . 19. . . . . . . . 21 Performance and Code Optimization 21. . . . . . . .5 Use M-Lint . . . . . . . . . . . . .4 Considerations when Using Cell Arrays 117 117 118 118 120 120 123 123 124 124 124 127 127 128 129 129 129 130 . . . . . . . .8 Vector and Matrix Functions 23. . . . . . . . . . . . . . . . . . . . . . . . . . . . .11 Flow Control . . . . . . . . . . . . . . . . . .3 Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23. . . . . . . . . . . . . . . . . . . . . . . . 23. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23. . . . . . . . . . . . . . . . . .1 General Math . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Replicating Simulation Data . . . . . . . . . . . . . . . . . . . . . . . 21. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 Special Matrices . . . . . . . . . . . . . . . . 131 22. . . . . . . .4 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . 20. . . . . . . . . . . . . . . . . . . . . . . . 19. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 19 Structures and Cell Arrays 19. .

. . . . . .16 23. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12 23. . . . . . . . . . . . . . . . . . . . . . . . . .19 23. . . . . . . . . . . . . . . . .15 23. . . . . . . Input/Output . . . . . . . . . . . . Graphics . . . . . . . . . . . . . . . . . . . 142 142 143 145 146 147 147 148 150 . . . . . . . . . .CONTENTS 7 23. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17 23. . . . . . . . . . . . Optimization . . . . . . . .13 23. . . . . . . Trigonometric Functions File System . . . . . . . . . . . . .18 23. . . . . . . . . . . . Date Functions . . . . . . . .20 Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . String Function . . . . . . . . MATLAB Speciﬁc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14 23. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8 CONTENTS .

Typewriter font is used to denote MATLAB commands and code snippets. please let me know and I’ll add examples as necessary. The history can also be scrolled through in the command window by pressing the up arrow (↑) key. is where commands are entered. MATLAB keywords such as if. using Microsoft’s Remote Desktop Client. functions are called and m-ﬁles – batches of MATLAB commands – are run. consult the information that accompanied your username.manor-road.Chapter 1 Introduction to MATLAB These notes provide a brief introduction to MATLAB. labeled 4. shows the ﬁles located in the current directory. and comments are in green. 1. abs and plot are highlighted in cyan. for and break are highlighted in blue and existing MATLAB functions such as sum. contains the command history (a display of commands recently executed). All topics relevant to the MFE curriculum should be covered at some basic level but if some important topic is missing or under-explained. There are four sub-windows visible. Hanselman (ISBN: 0131857142). The current directory window. and was the ﬁrst book I used – back when the title was Mastering MATLAB 5. On the right side of the command window is the workspace (3) reveals a list of the variables in memory.ox. labeled 1. The command window. see MATLAB: An Introduction with Applications by Amos Gilat (ISBN:0470108770) or Mastering MATLAB 7 by Bruce L. The ﬁrst book provides more examples for beginners while the second is comprehensive. labeled 2. Strings are highlighted in purple. This set of notes follows a few conventions. mrb-studentlab. Littleﬁeld and Duane C. ranging from basic concepts to advanced applications. or consult the IT help desk. The ﬁnal window. For more information on programming in MATLAB. In general both keywords and function names should not be used for variable names. The double arrow symbol >> is used to indicate the MATLAB command prompt and is the symbol used in the MATLAB command window.1 contains an image of the main MATLAB window.uk. MATLAB is available on the Economics department servers.ac. such as data loaded or variables declared. . For help using the RDC. Math font is used to denote algebraic expressions. The history can be copied and pasted into the command window to re-run commands.1 The Interface Figure 1. Normally these will include m-ﬁles and data. although only keywords are formally excluded from being redeﬁned.

cov. M-ﬁle names can include letters. and 4: Command History 1.2 The Editor MATLAB contains a syntax-aware editor that highlights code to improve readability and provides limited error checking.). although they must begin with a letter.10 Introduction to MATLAB Figure 1. The editor can be launched from the main window in one of two ways. either by clicking File>New>M-File or entering edit into the command window directly. std. To verify whether a name is already in use. end. >> which for built-in (C:\Program Files\MATLAB\R2009a\toolbox\matlab\lang\for) >> which mean C:\Program Files\MATLAB\R2009a\toolbox\matlab\datafun\mean. .2 contains an example of the editor and syntax highlighting. var. M-ﬁles can contain batches of commands or complete functions. 2: Current Directory. numbers and underscores. the command which ﬁlename can be used to list the ﬁle which would be executed use if ﬁlename was entered in the command window. The standard setup has four pains.1: Basic MATLAB Window. . Figure 1. . . while.m >> which mymfile .) and existing function names (mean. sum. 3: Workspace. else. for. 1: The command window. . . Names should be distinct from reserved words (if.

>> which mean -all C:\Program Files\MATLAB\R2009a\toolbox\matlab\datafun\mean. >> x=ones(3. Lines are still processed only nothing is returned to the command window. >> x=ones(3. The editor is a useful programming tool. ’mymfile’ not found.m C:\Program Files\MATLAB\R2009a\toolbox\finance\ftseries\@fints\mean.2: MATLAB editor.) is used at the end of a line to suppress the display of result of a command..1) . The semicolon (. Note the syntax highlighting. To understand the effect of a .m % timeseries method % fints method .m C:\Program Files\MATLAB\R2009a\toolbox\matlab\timeseries\@timeseries\mean. use the command which ﬁlename -all to produce a list of all matching ﬁles. To check whether a ﬁles already created is using duplicating the name of another function.2 The Editor 11 Figure 1.1).1. examine the result of these two commands. It can be used to create batch ﬁles or custom functions (both called m-ﬁles).

it may be useful to leave the semicolon off until the code is functioning as expected. . (dot-dot-dot) . % Every line must have a % % symbol before the comment . documenting unique approaches to solving a difﬁcult problem and are useful if the code needs to be shared. x = x + x * x . Two types of help are available from the command line: toolbox and function.x . while function speciﬁc help can be accessed by calling help function. for example help mean. ..). .g.3 Help MATLAB contains a comprehensive help system which is available both in the command window and in a separate browser. . Comments Writing clear comments is an essential practice when coding.x + exp(x) / log(x) * sqrt(2*pi). These two expressions are identical to the MATLAB interpreter. x = 7. The percentage symbol (%) is used to identify a comment. Comments assist in tracking completed tasks. is a special expression that can be used to break a long code expression across multiple lines in an m-ﬁle. such as debugging or examining the output of a particular command. The browser-based help is typically more complete and is both indexed and searchable. It exists purely to improve the readability of code.12 Introduction to MATLAB x = 1 1 1 It is generally a good idea to suppress the output of commands. It can be called by help toolbox where toolbox is the short name of the toolbox (e. optim. concatenates the next line onto the end of the present line when processing. etc. . without a second argument. . 1. x = 7. . stats. x = x + x * x . + exp(x) / log(x) * sqrt(2*pi). will produce a list of toolboxes. When a % is encountered processing stops on the current line and continues on the next line. Toolbox help returns a list of available functions in a toolbox. although in certain cases. help.. Block comments are not supported and so comment blocks must use a % in front of each line. % This is the start of a % comment block. .

selecting Help>Full Product Family Help at the top of the command window. Become familiar with the MATLAB Command Window.4 Demos MATLAB contains an extensive selection of demos. 2. The demos in the Graphics section are particularly entertaining. 1. Launch the editor and explore its interface. 1. Introduction.g. Launch the help browser and read the section MATLAB. doc mean). The documentation of a function can be directly accessed by entering doc function in the command window (e. 4. . enter demo in the command window. To access the list of available demos. or entering doc in the command window.5 Exercises 1.1. 3. Getting Started. Enter demo in the command window and play with some of the demos.4 Demos 13 The help browser can be accessed by hitting the F1 key.

14 Introduction to MATLAB .

x = y. although they can only contain numbers. Thus changes to y will not be reﬂected in the value of x in y = 1 and x = y. Assigning one variable to another assigns the value of that variable. letters (both upper and lower). x X X1 . The ﬁrst assigns 1 to x. >> x = y. are all valid assignments for x.Chapter 2 Basic Input Users are not required to manage memory and variables can be input with no setup. The generic form of an expression is Variable Name = Expression and expressions are processes by assigning the value on the right to the variable on the left.1 Variable Names Variable names can take many forms. y. the second assigns the value of another variable. For instance. not the variable itself. x = exp(y). They must begin with a letter and are CaSe SeNsItIve. >> x x = 1 >> y = 2. >> y = 1. For example. >> x x = 1 >> y y = 2 2. to x and the third assigns the output of exp(y) to x. and underscores (_). x = 1.

even if they are 1 by 1 (scalar). respectively.1 Vectors. 3. can be entered directly into the command window. The column vector. 1 An important exception to the “everything is a matrix” rule occurs in cell arrays. 4. . separating the rows with semicolons.3 Entering Matrices Matrices are just column vectors of row vectors. 7 8 9 enter the matrix one row at a time. to input 1 2 3 x = 4 5 6 . x = is entered using a less intuitive structure >> x=[1. [ and ] are reserved symbols which are interpreted as begin array and end array. 1 2 3 4 5 where . The mathematical notation x = [1 2 3 4 5] is entered as >> x=[1 2 3 4 5]. is interpreted as new row when used inside an square brackets ([ ]).2 Entering Vectors Almost all of the data used in MATLAB are matrices by construction.16 Basic Input X_1 x_1 dell dell_returns are all legal and distinct variable names. For instance. while x: 1X X-1 _x are not. which are matrices composed of other matrices (formally arrays of arrays or ragged (jagged) arrays). In the above input. 5]. K by 1 or 1 by K (vectors). 2. 2. See chapter 19 for more on the use and caveats to cell arrays. both row (1 by K ) and column (K by 1). 2.

such as a time-varying covariance matrices. depending on the size of each matrix dimension. Higher dimensional arrays can be useful for tracking matrix values through time.2. although they do have some useful applications. 2). This type of concatenation is bad for code performance and so it should be avoided by pre-allocating the data array using zeros (see page 47). they can be used for lazy vector construction using repeated concatenation. 2 as the third and leaves the second empty. For instance. 2. Empty matrices may be returned from functions in certain cases (e. 7 8 9]. Second. if some criteria is not met).2). suppose x = and 2 1 2 3 4 and y = 5 6 7 8 .2 2. occasionally in difﬁcult to predict ways. First. The latest version of MATLAB.5 Empty Matrices ([]) An empty matrix contains no elements. if possible. which passes x as the ﬁrst argument. For example >> x=[] x = [] >> x=[x 1] x = 1 >> x=[x 2] x = 1 x = 1 2 3 2 >> x=[x 3] is a legal operation that builds a 3-element vector by concatenating the previous value with a new value. higher dimension arrays cannot be directly allocated and so can only be constructed by calling functions such as zeros(2.4 Higher Dimension Arrays 17 >> x = [1 2 3 .4 Higher Dimension Arrays Multi-dimensional (N -dimensional) arrays are available for N up to about 30.g. Both horizontal and vertical concatenation are possible. vectors and matrices. x = []. . R2009b. empty matrices are needed for calling functions when multiple inputs are required but some are not used.6 Concatenation Concatenation is the process by which one vector or matrix is appended to another. Empty matrices often cause problems.[]. 2. provides an alternative method of passing empty arguments using a tilde (~). 4 5 6. for example std(x. Unlike scalars. 2.

Elements can be accessed by element number using parenthesis (x(#)). the elements of x can be accessed >> x=[1 2 3. it is important to be able to access the elements individually. the third is 7. and so on. This means elements are indexed by ﬁrst counting down rows and then across columns. >> x=[1 2. in the matrix 1 2 3 x = 4 5 6 7 8 9 the ﬁrst element of x is 1. 2. 7 8] z can be deﬁned in a natural way: >> z=[x. After deﬁning x. For instance. 4 5 6. needs to be constructed. the second element is 4. x and y can be horizontally concatenated in a similar fashion: >> z=[x z = 1 3 2 4 5 7 6 8 y] Note: Concatenating is the code equivalent of block-matrix forms in standard matrix algebra. Data in matrices is stored in column-major order. y] z = 1 3 5 7 2 4 6 8 This is an example of vertical concatenation. the fourth is 2.18 Basic Input z = x y . This can be accomplished by treating x and y as elements of a new matrix. 3 4] x = 1 3 y = 5 7 6 8 2 4 >> y=[5 6.7 Accessing Elements of Matrices Once a vector or matrix has been constructed. 7 8 9] x = 1 4 2 5 3 6 .

3) ans = 3 >> x(2. x([1 2]. The colon operator (:) plays a special role in accessing elements.:) is interpreted as all elements from x in row 2.:) will returns all columns from rows 1 and 2 of x. Double indexing of matrices is available using the notation x(#.2.:) 2 3 . x(1. For example. in which case the indices correspond directly to the order of the elements in x. >> x(1. will return the elements from x in rows 1 and 2 and columns 1 and 2.[1 2]). Similarly.1). it is interpreted as all elements in that dimension. vectors can be used to access elements of x. x(:. For instance. is interpreted as all elements from matrix x in column 1.1) ans = 4 >> x(3. #). >> x(1.:) returns x. Double : notation produces all elements of the original matrix and so x(:. while x([1 2]. Finally.7 Accessing Elements of Matrices 19 7 >> x(1) ans = 1 >> x(2) ans = 4 >> x(3) ans = 7 >> x(4) ans = 2 >> x(5) ans = 5 8 9 The single index notations works well if x is a vector. For instance.2) ans = 2 >>x(1.#).1) ans = 1 >> x(1. #. x(2.3) would return the element in the ﬁrst row of the second column of the third panel of a 3-D matrix x.:) ans = 1 >> x(2. x(#. When used.2.3) ans = 9 Higher dimension matrices can also be accessed in a similar manner. However single index notation is confusing when x is a matrix.

out2. the outputs must be encapsulated in brackets.). for example y=mean(x). . . For example. The important aspects of this structure are • If only one output is needed.:) ans = 1 4 7 >> x x = 1 4 7 ans = 1 4 ans = 2 8 ans = 1 7 2 8 3 9 3 9 2 5 2 5 8 3 6 9 2 5 8 3 6 9 5 6 >> x([1 2]. . such as in [y. in2.[1 2]) >> x([1 3]. • Both inputs and outputs must be separated by commas (.20 Basic Input ans = 4 >> x(:. .). Asking for more outputs than the function provides will result in an error. • The number of output variables determines how many outputs will be returned. The generic structure of a function call is [out1. the following are equivalent. in3.8 Calling Functions Functions calls have different conventions other expressions. • If multiple outputs are required. mean(y) and mean(var(x)) .[2 3]) >> x([1 3]. y = var(x). The most important difference is that functions can take more than one input and return more than one output.]=functionname(in1. out3. . index] = min(x).:) 2. brackets ([ ]) are optional. . • Inputs can be the result of other functions as long as only the ﬁrst output is required.

2. u = [1 1 2 3 5 8] v = 1 1 2 3 5 8 x = 1 0 0 1 1 2 3 4 y = 1 2 1 2 z = 3 4 3 4 1 2 1 2 w = x y x y 2. What command would pull [x.[?]) is the same as x .g.) 3. 4. 2. What command would pull y out of z ? List all alternatives. Details of important function calls will be clariﬁed as they are encountered. Input the following mathematical expressions into MATLAB. list all alternatives. . y] out of w? Is there more than one? If there are.9 Exercises 1.9 Exercises 21 • Inputs can contain only selected elements of a matrix or vector (e.[1 2]))). What command would pull x would of w ? (Hint: w([?]. mean(x([1 2] .

22 Basic Input .

1. 2000 would be 36526. is not numeric. consider importing a month of GE prices downloaded from Yahoo! Finance. especially dates.1 Importing Data Importing data ranges from moderately challenging to very difﬁcult. • Use another program. containing the dates.Chapter 3 Importing and Exporting Data Importing data into MATLAB can be challenging. The key to the import is to make certain the Excel ﬁle has a very particular structure: • One variable per column • A valid.xls. The key step to ensure a smooth import is to convert the dates from Excel dates to numbers. right click and choose format. select the dates. to manipulate data before importing. A few principles can simplify this task: • The ﬁle imported should contain numbers only. 3.xls and is presented in Figure 3.2 Robust Data Importing The simplest and most robust method to import data is to use a correctly formatted Excel ﬁle and the import wizard.2. This “clean” ﬁle can be found in GEPricesClean. the output should be similar to ﬁgure 3. To perform the conversion. such as Microsoft Excel. • Dates should be imported as numbers by ﬁrst formatting the columns as Excel Dates and then reformatting as a number (dates with base year 1900). For example. depending on the data size and format. If the conversion was performed correctly. This data ﬁle nearly ﬁts the requirement although the ﬁrst column. with the exception of the ﬁrst row which should contain the variable name. distinct variable name for the column in the ﬁrst row • All data in the column must be numeric. • Each column of the spreadsheet should contain a single variable. January 1. As an example. The original data can be found in GEPrices. 3. . Select “Number” from the dialog box the pops up.

2007. . Make certain the ﬁle conforms to the rules above and try again. This will trigger the dialog in ﬁgure 3. Next. 3. First. To load the data.1: The raw data as taken from Yahoo! Finance.xls’). 1 If this pane is absent. This structure will prevent the Excel ﬁle from being parsed correctly by MATLAB. right click on the ﬁlename and select Import (see ﬁgure 3. use the command >> data = xlsread(’deciles. which contains returns for the 10 CRSP deciles from January 1. it can be enabled in the Desktop tab along the top of the MATLAB window. select the Current Directory browser in the upper left pane of the main window. Once the Excel ﬁle has been formatted.xls. the ﬁnal step is to import it. To complete the import. change the Current Directory to the directory with the Excel ﬁle to be imported. deciles. make sure Create vectors from each column using column names is chosen and click ﬁnish.3 Reading Excel Files Data in Excel sheets can be imported using the function xlsread from the command window.4. The ﬁrst column contains the dates while columns 2 through 11 contain the portfolio returns from decile 1 through decile 10 respectively. To import the ﬁle.3). Most of the columns are well formatted with variable names in the ﬁrst row and numeric content. If the import fails the most likely cause is the format of the Excel ﬁle. Accompanying this set of notes is an Excel ﬁle.1 The Excel ﬁle should be present in this view. 2004 to December 31. However the date column contains Excel dates and not numeric.24 Importing and Exporting Data Figure 3.

3.3 Reading Excel Files

25

Figure 3.2: This correctly formatted ﬁle contains only the variables to import: date, close and volume. Note that the date column has been converted from Excel dates to numbers so January 3, 2007 appears as 39085.

This command will read the data in sheet1 of ﬁle deciles.xls and assign it to data. xlsread can handle a number of other situations, including reading sheets other than sheet1 or reading only speciﬁc blocks of cells. For more information, see doc xlsread. Data can be exported to an Excel ﬁle using xlswrite. Extended information about an Excel ﬁle, such as sheet names and can be read using the command xlsflinfo. Note: MATLAB and Excel do not agree about dates. MATLAB dates are measured as days past January 0, 0000while Excel dates are measured relative to December 31, 1899. In MATLAB serial date 1 corresponds to January 1, 0000 while in Excel day 1 corresponds to January 1, 1900. To convert imported Excel dates into MATLAB dates, datenum(’30DEC1899’) must be added to the column of data representing the dates. Returning to the example above,

>> [A,finfo]=xlsfinfo(’deciles2.xls’) A = Microsoft Excel Spreadsheet finfo = ’deciles’ >> data = xlsread(’deciles2.xls’,’deciles’,’A2:K1257’); >> dates = data(:,1); >> datestr(dates(1)) ans = 03-Jan-0104 >> dates = dates + datenum(’30DEC1899’);

26

Importing and Exporting Data

Figure 3.3: To import data, select the Current Directory view, right click on the Excel ﬁle to be imported, and select Import. This will trigger the import wizard in ﬁgure 3.4.

>> datestr(dates(1)) ans = 02-Jan-2004

**Alternatively, the function x2mdate can be used to convert the dates.
**

>> data = xlsread(’deciles2.xls’,’deciles’,’A2:K1257’); >> dates = data(:,1); >> datestr(dates(1)) ans = 03-Jan-0104 >> dates = x2mdate(dates); >> datestr(dates(1)) ans = 02-Jan-2004

3.4 CSV Data

27

Figure 3.4: As long as the data is correctly formatted (see ﬁgure 3.2), the import wizard should import the data and create variable with the same name as the column headers. To complete this step, make sure the second radio button is selected (Create vectors from each column using column names) and then select Finish.

This example uses a ﬁles deciles2.xls which contains the sheet deciles. Opening the ﬁles in Excel shows that deciles contains column labels as well as the data. To import data from this ﬁle, xlsread needs to know to take the data from deciles in cells A2:K1275 (upper left and lower right corners of block). Running the command xlsread(’deciles2.xls’, ’deciles’, ’A2:K1257’) does this. Finally, the disagreement in the base date is illustrated and the correction is shown to work. For more on dates, see Chapter 17.

3.4

CSV Data

Comma-separated value (CSV) data is similar to Excel data. Note that CSV ﬁles must contain only numeric values. If the ﬁle contains strings, such as variable names, the import will fail. The command to read CSV data is essentially identical to the command to read Excel ﬁles,

% This command fails since deciles.csv contains variable names in the first row >> data = csvread(’deciles.csv’)

**Like xlsread, other forms can begin reading at a speciﬁc cell
**

% This command works since it skips the first row >> data = csvread(’deciles.csv’,1,0)

**or to read speciﬁc blocks of cells
**

>> data = csvread(’deciles.csv’,1,0,[1 0 100 10]);

Data can be exported to CSV using csvwrite.

mat) The native ﬁle format is the MATLAB data ﬁle.txt’.7 Manually Reading Poorly Formatted Text MATLAB can be programmed to read virtually any text format since it contains functions for parsing and interpreting arbitrary text containing numeric data. but it is recommend to keep data ﬁles as simple as possible and to only use tab delimited text ﬁles (such as the example deciles. 3. dates and text on each line.txt’). The standard command is textread which has a syntax similar to xlsread. data = textread(’deciles. 2001.2001 through January 31. %Pre-allocate the data dates = zeros(count-1. . See below for saving data in mat format.28 Importing and Exporting Data 3. It is too large to use in Excel and has both numbers.1). or mat ﬁle. if ~ischar(line) break end count=count+1. %Count number of lines count=0. For instance. while 1 line=fgetl(fid).mat There is no need to specify an input variable as the mat ﬁle contains both variable names and data. fid=fopen(’IBM_TAQ. The ﬁle IBM_TAQ. Data from a mat ﬁle is loaded by entering load deciles. some data is only available in formats where reading in data line-by-line is the only option.5 Text Reading in text is also simple if the ﬁle only contains numbers.’rt’). textread has been updated in the function textscan which can read both numeric and string data.txt). textread can handle a variety of data formats. See doc textread for further information.6 MATLAB Data Files (. 3. end %Close the file fclose(fid). In this case. Reading poorly formatted data ﬁles is an advanced technique and should be avoided if possible. the only possibility is to write a program to read the ﬁle line-by-line and to process each line separately. the standard import method fails if the raw data is very large (too large for Excel) and is poorly formatted. The following code block shown how the data in this ﬁle can be parsed. However.txt contains a simple example of data that is difﬁcult to import. This ﬁle was downloaded from WRDS and contains all prices for IBM from the TAQ database in the interval January 1.

second=str2double(temptime(colons(2)+1:length(temptime))). %Use count to index the lines this pass count=1. minutes or and seconds to numbers hour=str2double(temptime(1:colons(1)-1)). they delimit the file commas = strfind(line.1). %If the line is not a character value we’ve reached the end of the file if ~ischar(line) break end %Find all the commas.’). %Times are colon separates. %Get one line to throw away since it contains the column labels line=fgetl(fid).txt’. %while 1 and break work well when reading test while 1 line=fgetl(fid). end fclose(fid).’.1). %Times are between the second and third temptime=line(commas(2)+1:commas(3)-1).7 Manually Reading Poorly Formatted Text 29 time = zeros(count-1. times and price variables using zeros • Rereads the ﬁle parsing each line by the location of the commas using strfind to locate the delimiting character • Uses datenum to convert string dates to numerical dates • Uses str2double to convert strings to numbers . %Increment the count count=count+1. %Reopen the file fid=fopen(’IBM_TAQ. price = zeros(count-1. %Convert these values to seconds past midnight time(count)=hour*3600+minute*60+second.3. %Dates are places between the first and second commas dates(count)=datenum(line(commas(1)+1:commas(2)-1).’:’). minute=str2double(temptime(colons(1)+1:colons(2)-1)).’rt’). %Convert the text representing the hours. %Read the price from the last comma to the end of the line and convert to number price(count)=str2double(line(commas(3)+1:commas(4)-1)).’yyyymmdd’). so they need further parsing colons=strfind(temptime. This block of code does a few thing: • Open the ﬁle directly using fopen • Reads the ﬁle line by line using fgetl • Counts the number of lines in the ﬁle • Pre-allocates the dates.

fscanf. fgetl.8 Reading Poorly Formatted Text Using textscan textscan is a fast method to read ﬁle that contain mixed numeric and string data.1800 >> data{5}(1) ans = 100 [558986x1 double] [558986x1 double] {558986x1 cell} Note that the time column would need further processing to be converted into a useful format. and textscan. For more on reading poorly formatted data ﬁle. {} indicates that cell array are being used. where numeric columns are stored as vectors while string values (the ticker and the time in this example) are stored as cell arrays of strings. fid = fopen(’IBM_TAQ. see the documentation for fopen. and second each row must contain the same type of data – that is the ﬁle must not mixing strings with numbers in a column. The use of curly braces.csv’). >> data = Columns 1 through 3 {558986x1 cell} Columns 4 through 5 [558986x1 double] >> data{1}(1) ans = ’IBM’ >> data{2}(1) ans = 20070103 >> data{3}(1) ans = ’9:30:03’ >> data{4}(1) ans = 97. . ’. A text ﬁle must satisfy some constraints in order for textscan to be useful. See chapter 19 for more on accessing the values in cell arrays. The arguments to textscan instruct the function that the a line is formatted according to string-numberstring-number-number where %s indicates string and %f indicates number. and that the ﬁrst line is a header and so should be skipped. that the columns are delimited by a comma.’. First. dlmread. IBM_TAQ. 1) fclose(fid). the ﬁle must be regular in that it has the same number of columns in every row. ’%s %f %s %f %f’. fread. ’delimiter’. See chapter 18 for more on string manipulation.txt is satisﬁes these two constraints and so can be read using the command block below.30 Importing and Exporting Data • Closes the ﬁle directly using fclose 3. The data read in by textscan is returned as a cell array. data = textscan(fid. ’HeaderLines’.

mat containing all variables in memory. csvwrite and dlmwrite. It allow users to load data in one format and output some or all of the data in another. SP500 and XOM. >> save filename var1 -ascii -double would save the data in var1 in a tab-delimited text ﬁle. save it and any changes in the native MATLAB data format using save >> save filename This will produce the ﬁle ﬁlename. 5. 3. StatTransfer can make some hard-to-manage situations (e. including MATLAB. use >> save filename var1 var2 var3 which saves the ﬁle ﬁlename. The ﬁle exercise3. Save a MATLAB data ﬁle exercise3 with all three variables. Use xlsread to read the ﬁle saved in the previous exercise. 6. poorly formatted data) substantially easier. var1=[var2 var3]. Parse returns into three variables. the return on the S&P 500. . 7. Export the variable output_data to a new . The restriction to a single variable should not be seen as a severe limitation since var1 can always be constructed from other variables (e. For example.g.11 Exercises 1. use the : operator).mat containing var1. Exporting more than one variable results in a poorly formatted ﬁle that may be hard to import into another program. To save a subset of the variables in memory. dates. ﬁlename can be replaced with any valid ﬁlename. StatTransfer has a comprehensive help ﬁle to provide assistance.9 Stat Transfer StatTransfer is available on the servers and is capable of reading and writing approximately 20 different formats. Construct a new variable. Create another new variable. convert the date to a number and save the ﬁle. Using Excel. var2 and var3 . output_data as a horizontal concatenation of dates and sum_returns. 2. Save a MATLAB data ﬁle dates with only the variable dates.3.000). They should be around 35. Excel. 3. It is generally a good practice to only export one variable at a time using this method. (Hint: Format the cells with dates as numbers. 4. and the return on XOM (ExxonMobil).g. See the help available for xlswrite. GAUSS.xls contains three columns of data. 3. Exporting Data Data can be exported to a tab-delimited text ﬁles using save with the arguments -double-ascii. the date. (Hint. Stata. sum_returns as the sum of SP500 and XOM.10 Exporting Data Saving Data Once the data has been loaded. CSV and text ﬁles. Load in the three series into a new variable names returns. Alternative methods to export data include xlswrite..xls ﬁle using xlswrite. SAS.9 Stat Transfer 31 3.

32 Importing and Exporting Data .

2 Matrix Addition (+) and Subtraction (-) Addition and substraction require x and y to have the same dimensions or to be scalar.y x * y x/y x \ y x ∧ y Algebraic x +y x −y xy x y y x \ ∧ xy When x and y are scalars. the behavior of these operators is obvious. When x and y are matrices.1 Operators These standard operators are available: Operator + * / Meaning Addition Subtraction Multiplication Division (Left divide) Right divide Exponentiation Example x + y x .j)=x(i.j). For instance. operations that are not legal in linear algebra are not legal in MATLAB.Chapter 4 Basic Math Mathematical operations closely follow the rules of linear algebra. 4. z=x+y produces a matrix with z(i.j)=x+y(i. things are a bit more complex. matrices must conform along their inside dimensions to be multiplied.j)+y(i. 4. Operations legal in linear algebra are legal in MATLAB. If x is scalar and y is a matrix. Suppose z=x+y: y Scalar x Matrix Scalar Any z =x +y Any z i j = y + xi j Matrix Any z i j = x + yi j Both Dimensions Match z i j = x i j + yi j . If they are both matrices.j). attempting to multiply nonconforming matrices produces an error. z=x+y results in z(i.

If x is scalar and y is a matrix. Division ﬁnds z as the solution to this set of linear equations by least squares. then z=x*y produces z(i. Similarly.3 Matrix Multiplication (*) Multiplication requires the inside dimensions to be the same or for one input to be scalar. Suppose z=x\y: .34 Basic Math Note: Note: These conform to the standard rules of matrix addition and substraction.4 Matrix Division (/) Matrix division is not generally deﬁned in linear algebra and so is slightly tricker. a M by L vector. Suppose z=x/y: y Scalar x Scalar Any x z = y Any x z i j = yi j Matrix Left Dimensions Match z = (y y )−1 y x Left Dimensions Match z = (y y )−1 y x Matrix Note: Like linear regression. Suppose z=x*y: y Scalar x Matrix Scalar Any z = xy Any z i j = y xi j Matrix Any z i j = x yi j Inside Dimensions Match M z i j = k =1 x i k y k j Note: These conform to the standard rules of matrix multiplication. y*x requires L = N .j). 4. The intuition for matrix division comes from thinking about a set of linear equations. 4. x*y requires M = K . matrix left division is only well deﬁned if y is nonsingular and thus has full rank.5 Matrix Right Divide (\) Matrix right division is simply the opposite of matrix left division. If x is N by M and y is K by L and both are non-scalar matrices. 4.j)=x*y(i. and so z = (y y )−1 (y x ). Suppose there is some z . such that yz = x where x is N by M and y is N by L. x i j is the element from row i and column j of x .

6 Matrix Exponentiation (∧ ) 35 y Scalar x Matrix Scalar Any y z = x Right Dimensions Match z = (x x )−1 x y Matrix Any yi z i j = xj Right Dimensions Match z = (x x )−1 x y Note: Matrix right division is only well deﬁned if x is nonsingular.∧ ) all have dot forms. .∧ diag(D)) * inv(V) where V is the matrix of eigenvectors and D is a diagonal matrix containing the corresponding eigenvalues of y.6 Matrix Exponentiation (∧ ) Matrix exponentiation is only deﬁned if at least one of x or y are scalars. operator (read dot operator) changes matrix operations into element-by-element operations.j).j) z(i.j) Note: These are sometimes called the Hadamard operators.1 4.j)=x(i. If y is not integer. and can be nested to create complex expressions./y z=x.*y z=x.j) = x(i. Multiplication (. 1 If x is a scalar and y is a square matrix. z=x*y results in usual matrix multiplication where z(i.*x (y times). z=x.*. .4.j) z(i.j) = x(i. (dot) operator The .j)∧ y(i.\).j)\y(i. 4.10 on Operator Precedence for more information on the order mathematical expressions are evaluated.*). this function involves eigenvalues and eigenvalues.\ y z=x. Suppose x and y are N by N matrices.j). 4.j)=x(i. then x∧ y is deﬁned as V * diag(x. and z=x*x*. y ∧ z(i.j)/y(i.8 . right division (.j)=x(i. Suppose z=x∧ y: y Scalar x Matrix Scalar Any z = xy x Square z = xy Matrix y Square Not useful N/A Note: In the case where x is a matrix and y is an integer. and exponentiation (.7 Parentheses Parentheses can be used in the usual way to control the order in which mathematical expressions are evaluated.j) * y(i./).j)=x(i.:) * y(:. division (. while z = x .j)*y(i. See section 4. .* y produces z(i. especially .j) z(i.

4. consider the expression (-4).since there is only 1 operation. compute the values of u + v .11 Exercises 1. u v and xy 2. Is x\ 1 legal? If not. This is an instance of a unary .36 Basic Math 4. show it. how can the second be changed so they are equal. What restrictions on the dimensions of w. x. What is the value of -2∧ 4? What about (-2)∧ 4? . . Note: Unary operators are + or .10 Operator Precedence Computer math.∧ y be the same? 6. : <. x∧ y∧ z is interpreted as (x∧ y)∧ z. Is a*b+a*c the same as a*b+c? If so. Is x∧ 2+2*x*y+y∧ 2 the same as either above? 5. \. if x is an M by N matrix. When will x∧ y and x. Compute the values (x+y)∧ 2 and x∧ 2+x*y+y*x+y∧ 2. Using the matrices entered in exercise 1 of chapter 2.operations that apply to a single element. All Exponentiation Negation (Logical) Unary Plus.*. v u . x’ is its transpose with dimensions N by M .∧ Name Parentheses Transpose. For instance.− *. ∼= \& | \&\& || In the case of a tie. ==. >. <=. . What about x/1? 3. Unary Minus All multiplication and division Addition and subtraction Colon Operator Logical operators Element-by-Element AND Element-by-Element OR Short Circuit AND Short Circuit OR Rank 1 2 3 3 4 5 6 7 8 9 10 11 ∼ +. The order of evaluation is: Operator ( ) ’. / . For example. 4. ∧ . (-4)∧ 2 produces 16. Suppose a command x∧ y*w+z was entered. -4∧ 2 produces -16 since ∧ has higher precedence than unary negation and so is interpreted as -(4∧ 2) . like standard math. 7. >=. For example. . y and x must be true for this to be a valid statement? 8.9 Transpose Matrix transpose is expressed using the ’ operator. why not. Are they the same? 4. has operator precedence which determined how mathematical expressions such as 2∧ 3+3∧ 2/7*13 are evaluated. operations are executed left-to-right. -4 * -4 produces 16 since it is interpreted as (-4) * (-4). v + u ./ . . if not.\ +.

where DIM is the dimension. use z=size(x.2) depending on whether the number of rows of the number of columns is required. If y is T by K .1) returns T while z=size(x.1) . use z=length(x). Using length is risky since the value it returns can be the number of columns or the number of rows.2) returns K . z=size(x.Chapter 5 Basic Functions This section provides a reference for a set commonly used functions and a discussion of how they behave. T > K . length To ﬁnd the size of the maximum dimension of x. z = T .DIM ). >> x=[1 2 3. z = K . so if x is T by K . If K > T . Alternatively. It is better practice to use size(y. 4 5 6] x = 1 4 ans = 3 >> length(x’) ans = 3 2 5 3 6 >> length(x) size To determine the size of one dimension of a matrix. Note that dimension 1 is the number of rows while dimension 2 is the number of columns.1) and size(y. >> x=[1 2 3. 4 5 6] x = 1 4 ans = 2 2 5 3 6 >> size(x. depending on which is larger. s=size(x) returns a vector s with the size of each dimension.

i). K use the command min(x).i) + . i = 1.i) + x(2. If x is a matrix. 2. so z(i) = sum(x(:. min x i t . . min(x) is scalar.2) ans = 3 >> s=size(x) s = 2 3 sum To compute the sum matrix. T z = t =1 xt use the command sum(x). sum will add all elements of x whether it is a row or column vector. Note: If x is a vector. 4 5 6] x = 1 4 >> min(x) ans = 1 >> min(x’) ans = 1 4 2 3 2 5 3 6 .i)) = x(1. . 4 5 6] x = 1 4 >> sum(x) ans = 5 >> sum(x’) ans = 6 15 7 9 2 5 3 6 min To ﬁnd the minimum element of a vector or the rows of a matrix. >> x=[1 2 3. min(x) is a K by 1 vector containing the minimum values of each column.38 Basic Functions >> size(x. . If x is a vector. >> x=[1 2 3. + x(T. z=sum(x) returns a K by 1 vector containing the sum of each column. . . .

K use the command max(x). If x is a vector. If x is a vector. .7183 54. sort(x) is a matrix of the same size where each column is sorted from smallest to largest. .39 max To ﬁnd the maximum element of a vector or the rows of a matrix. If x is a matrix.4288 2 5 3 6 .j)).4132 20.5982 7. 4 5 6] x = 1 4 >> exp(x) ans = 2. i = 1. max x i t . max(x) is a K by 1 vector containing the maximum values of each column. use the command sort(x). z=exp(x) returns a vector or matrix the same size as x where z(i. 2. sort To sort the values of a vector or the rows of a matrix from smallest to largest. max(x) is scalar.0855 403. >> x=[1 2 3. sort(x) is vector where x(1)=min(x) and x(i)≤x(i+1). >> x=[1 5 2.3891 148.j)=exp(x(i. If x is a matrix. 4 3 6] x = 1 4 >> sort(x) ans = 1 4 >> sort(x’) ans = 1 2 5 3 4 6 3 5 2 6 5 3 2 6 exp To take the exponential of a vector or matrix (element-by-element). ex use exp. . .

√ xi j use sqrt.7321 2.4142 2.j)).3863 0. 4 5 6] x = 1 4 2 5 3 6 . >> x=[1 2 3. z = T t =1 xt T use the command mean(x). z=log(x) returns a vector or matrix the same size as x where z(i.j)=log(x(i. so z(i) = sum(x(i. mean will compute the mean of x whether it is a row or column vector.0000 2.j)).0986 1.0000 1.7918 2 5 3 6 sqrt To compute the element-by-element square root of a vector or matrix. >> x=[1 2 3.2361 1.∧ (1/2). mean To compute the mean of a vector or matrix.40 Basic Functions log To take the natural logarithm of a vector or matrix.6931 1.j)=sqrt(x(i. z=sqrt(x) returns a vector or matrix the same size as x where z(i. >> x=[1 2 3.:)) / Note: If x is a vector. z=mean(x) is a K by 1 vector containing the means of each column.4495 2 5 3 6 Note: This command produces the same result as z=x. ln x use log. 4 5 6] x = 1 4 >> log(x) ans = 0 1.6094 1. 4 5 6] x = 1 4 >> sqrt(x) ans = 1.

5000 2 5 3 6 cov To compute the sample covariance of a vector or matrix ˆ Σ= T t =1 (xt ¯ ¯ − x) (xt − x) T −1 use the command cov(x).5000 4.5000 4. var(x) is scalar.5000 >> mean(x’) ans = 2 5 3.41 >> mean(x) ans = 2.5000 4. var(x) is a K by 1 vector containing the sample variances of each column.5000 4. If x is a vector. Note: This command uses T − 1 in the denominator unless an optional second argument is used. cov(x) is scalar (and is identical of var(x)). If x is a matrix.5000 var To compute the sample variance of a vector or matrix.5000 >> var(x’) ans = 1 1 4. If x is a vector. >> x=[1 2 3. Note: This command uses T − 1 in the denominator unless an optional second argument is used. cov(x) is a K by K matrix with sample variances in the diagonal elements and sample covariances in the off diagonal elements. If x is a matrix. x = 1 4 >> cov(x) ans = 4. 4 5 6] x = 1 4 >> var(x) ans = 4. ˆ σ = 2 T t =1 (x t ¯ − x )2 T −1 use the command var(x).5000 4.5000 4.5000 2 5 3 6 .5000 4.5000 4.5000 4.5000 4.

4 5 6] x = 1 4 ans = 0 ans = 0 0 0 0 >> skewness(x’) 2 5 3 6 >> skewness(x) . If x is a vector. T ¯ 3 t =1 (x t −x ) skew = T ˆ σ3 use the command skewness(x). >> x=[1 2 3. and is equivalent to sqrt(var(x)). skewness(x) is a K by 1 vector containing the sample skewness of each column. T t =1 (x t ˆ σ= ¯ − x )2 T −1 use the command std(x). >> x=[1 2 3. Note: This command always uses T − 1 in the denominator.1213 2. 4 5 6] x = 1 4 >> std(x) ans = 2. std(x) is scalar. If x is a matrix.1213 >> std(x’) ans = 1 1 2. If x is a vector. If x is a matrix. std(x) is a K by 1 vector containing the sample standard deviations of each column.42 Basic Functions >> cov(x’) ans = 1 1 1 1 std To compute the sample standard deviation of a vector or matrix. skewness(x) is scalar.1213 2 5 3 6 skewness To compute the sample skewness of a vector or matrix.

ﬁrst:last and ﬁrst:increment:last.g. ﬁrst + 1. The other is to create a row vector with evenly spaced points. These examples to show how this construction works: >> x=1:5 x = 1 >> x=1:3. T ¯ 4 t =1 (x t −x ) κ= T ˆ σ4 use the command kurtosis(x).5000 1 1 >> kurtosis(x’) 2 5 3 6 >> kurtosis(x) : operator The : operator has two uses.1:.43 kurtosis To compute the sample kurtosis of a vector or matrix. In common usage.:)) to be accessed and has previously been described. 4 5 6] x = 1 4 ans = 1 ans = 1. The basic form.5000 1. Consider these two examples: >> x=0:. . x(1. . >> x=[1 2 3. In this context. kurtosis(x) is scalar.5 x = 1 >> x=-4:6 x = -4 -3 -2 -1 0 1 2 3 4 5 6 2 3 2 3 4 5 The second form for the : operator includes an increment. produces a row vector of the form [ﬁrst. ﬁrst:last. . ﬁrst and last will be integers and N =last-ﬁrst. ﬁrst + N (increment)] where N is the largest integer such that ﬁrst+N(increment)≤last. The ﬁrst allows elements in a matrix or vector (e. If x is a matrix. . ﬁrst + 2(increment). The resulting sequence will have the form [ﬁrst. kurtosis(x) is a K by 1 vector containing the sample kurtosis of each column. ﬁrst + increment.5 . If x is a vector. ﬁrst + N ] where N is the largest integer such that ﬁrst+N ≤last. . . the : operator has two forms.

the resulting sequence will have the form [lower.upper.2832 -9.4248 -2 -3 -4 -5 >> x=0:-pi:-10 Note: ﬁrst:last is the same as ﬁrst:1:last where 1 is the increment. lower + inc. >> x=-1:-1:-5 x = -1 x = 0 -3.upper . If inc is deﬁned as inc=(upper-lower)/(N -1). linspace linspace is similar to the : operator.6667 1. lower + (N − 1)inc] and the command linspace(lower.3000 0.N)-lower:(upper-lower)/(N-1):upper The second line is interpreted (correctly. The generic form is linspace(lower . . lower + 2inc. >> linspace(lower. For instance. linspace produces a row vector with a predetermined number of nodes.upper. .N) will produce the same output as lower:(upper-lower)/(N-1):upper.N)-(lower:(upper-lower)/(N-1):upper) ans = 1.0e-015 * 0 ans = 0 0.2832 9. >> lower=0. . For example. the general form is unchanged but he stopping condition changes to N is the largest integer such that ﬁrst+N (increment)≥last.N ) where lower and upper are the two bounds of the series and N is the number of points to produce.1416 -6.5000 The increment does not have to be positive.0000 0 -0.1416 6. If a negative increment is used.1000 0.2000 0. Note: Remember : is a low precedence operator so operations involving : should always enclosed in parenthesis if there is anything else on the same line. Rather than producing a row vector with a predetermined increment.upper.44 Basic Functions x = 0 >> x=0:pi:10 x = 0 3.4248 0.3333 0. based on its rules) as >> (lower:(upper-lower)/(N-1):upper-lower):(upper-lower)/(N-1):upper . consider: >> N=4. >> upper=1.1110 0 >> linspace(lower.4000 0. Failure to do so can result in undesirable or unexpected behavior.

upper.6416 10. upper. 6. Repeat exercise 1 on this matrix. Compute the mean of returns’. logspace(lower. variance. 0. standard deviation. 3. Load the MATLAB data ﬁle created in the Chapter 4 exercises and compute the mean.4) ans = 1. Create a new matrix. 1. Using both the : operator and linspace. skewness and kurtosis of both returns (SP500 and XOM).5.99. .∧ linspace(lower. Find the max and min of the variable SP500 (see the Chapter 3 exercises). returns = [SP500 XOM]’. >> logspace(0. .1. 2.02. N). Create a custom logspace using the natural log (base e ) rather than the logspace created in base 10 (which is what logspace uses). Verify that the min corresponds to the ﬁrst value of this sorted series and the max corresponds to the last Hint: Use length or size.1 Exercises 45 logspace logspace produces points uniformly distributed in log10 space.1544 4.01. create the sequence 0. 4. .0000 2. . Create a new variable SP500sort which contains the sorted values of this series. 0.1 Exercises 1. N) is the same as 10.0000 5. Hint: Use linspace AND exp. . . 5.

46 Basic Functions .

N=10. one containing all zeros and one containing only ones. 2. How could these be replaced with repmat? .g. oneMatrix = ones(N. An identity matrix is always square so it only takes one argument. eye eye generates an identity matrix (matrix with ones on the diagonal. x = zeros(N. N and M must have been previously deﬁned (e. zeros every where else).M) will generate a matrix of 1s with N rows and M columns. the number of rows and the num- ber of columns. 3. Note: To use the function call above. Take the exponential of this matrix. of size 10 × 5. In = eye(N) zeros zeros produces a matrix of 0s in the same way ones produces a matrix of 1s. and is useful for initializing a matrix to hold values generated by another procedure. Multiply these two matrices in both possible ways.M=7). Produce an identity matrix of size 5.M) 6. element-by-element. 4. Produce two matrices. ones ones generates a matrix of 1s and is generally called with two arguments.1 Exercises 1.Chapter 6 Special Matrices Commands are available to produce a number of useful matrices.

48 Special Matrices .

suppose X was a matrix X = and the block matrix Y = X X X X X X 1 2 3 4 was needed. repmat replicates a matrix according to a speciﬁed size vector.1 Matrix Manipulation repmat repmat. For example. 3 4]. To understand how repmat functions. 7. N ) where X is the matrix to be replicated.Chapter 7 Matrix Functions Some functions operate exclusively on matrix inputs. M . repmat has two clear advantages over manual allocation: First.2. Manual matrix construction becomes tedious and error prone with as few as 5 rows and columns. However. >> y = [x x x. are two of the most useful non-mathematical functions. >> y = repmat(x. along with reshape. repmat can be executed using on some parameters determined at run-time. Some are mathematical in nature. while other are functions for manipulating the elements of a matrix. . x x x].3). and N is the number of columns in the new block matrix. imagine forming a matrix composed of blocks. The generic form of repmat is repmat(X . 3 4]. for instance computing the eigenvalues and eigenvectors. y could also be constructed with repmat by >> x = [1 2. M is the number of rows in the new block matrix. such as the number of explanatory variables in a model and second repmat can be used for arbitrary dimensions. This could be accomplished by manually constructing y as >> x = [1 2.

2.1. If the input is a vector. Note that the number of elements cannot change. reshape can transform an M by N matrix x into an K by L matrix y as long as M N = K L. Elements in matrices are counted ﬁrst down and then across columns. it will return a matrix containing the elements of the diagonal along the vector. x (1) = y (1). Consider the following example: >> x = [1 2. The most useful call to reshape switches a matrix into a vector or vice versa.4. 3 4].4) z = 1 w = 1 3 2 4 3 2 4 >> w = reshape(z. For example >> x = [1 2. it will return a column vector containing the elements of the diagonal. and so on.1) y = 1 3 2 4 >> z = reshape(y. preserving the number of elements. If the input is a square matrix. 3 4]. x = 1 3 y = 1 4 >> z=diag(y) z = 1 0 0 4 2 4 >> y = diag(x) . x (2) = y (2).2) The crucial implementation detail of reshape is that matrices are stored using column-major notation.50 Matrix Functions reshape reshape transforms a matrix with one set of dimensions and to one with a different set. reshape will place elements of the old matrix into the same position in the new matrix and so after calling reshape. >> y = reshape(x. diag diag can produce one of two results depending on the form of the input.

2 Linear Algebra Functions 51 7. inv inv computes the inverse of a matrix. trace trace computes the trace of a square matrix (sum of diagonal elements) and so trace(x) equals sum(diag(x)). Two output arguments are required in order compute both the eigenvalues and eigenvectors.7. z =x ⊗y and is written as z = kron(x. kron kron computes the Kronecker product of two matrices. The Cholesky factor is a lower triangular matrix and is deﬁned as C in CC =Σ where Σ is a positive deﬁnite matrix. .2 chol Linear Algebra Functions chol computes the Cholesky factor of a positive deﬁnite matrix. inv(x) can alternatively be computed using x∧ (-1). eig eig computes the eigenvalues and eigenvector of a square matrix. det det computes the determinant of a square matrix.y).val]=eig(x). [vec.

52 Matrix Functions .

7977 × 10308 and −1. All numeric software has precision limited and MATLAB is not different. NaN stands for Not a Number. For instance. NaNs are created whenever a function produces a result that cannot be clearly deﬁned as a number or inﬁnity.2251 × 10−308 .2204 × 10−16 .2204 × 10−16 are numerically the same.7977 × 10308 .2251 × 10−308 and 2. The easiest to understand are the upper and lower limits. This value is returned from the command eps and may vary based on the type of CPU and/or the operating system used. Inf represents inﬁnity and Inf is distinct from -Inf. Numbers larger (in absolute value) than these are Inf. the hardest concept to understand about numerical accuracy is the limited relative precision.Chapter 8 Inf. which are 1. To explore the role of eps. examine the results of the following: >> x=1 x = 1 >> x=x+eps/2 x = 1 >> x-1 ans = 0 >> x=x+2*eps x = 1 >> x-1 ans = 4. The relative precision is 2. However. examine the following output >> x=10 x = 10 >> x+2*eps .2251 × 10−308 are numerically 0. inf/inf results in NaN. Numbers between −2. for instance 1/0 or exp(1000).4408e-016 To understand what is meant by relative range. The smallest non-zero number that can be expressed is 2. Inf can be constructed in a number for ways. NaN and Numeric Limits Three special expressions are reserved to indicate certain non-numerical “values”. Numbers which are outside of a relative range of 2.

However in the second example.1+eps/10? 3. NaN and Numeric Limits ans = 10 >> x-10 ans = 0 In the ﬁrst example. Is 1e120 (1 × 10120 ) different from 1e120+1e102? (Hint: Test with ==) . What is the value of eps/10? 3.1 Exercises 1. eps/2 < eps so it has no effect while 2*eps > eps so it does. it has no effect when added. What is the value of log(exp(1000)) both analytically and in MATLAB? Why do these differ? 2. 8. This is a very tricky concept to understand.1 different from . 2*eps/10 < eps. Is . but failure to understand numeric limits can results in errors in code that appears to be otherwise correct.54 Inf.

. end blocks) which will be discussed later. The following table examines the behavior when x and/or y are scalars or matrices. >=. say y. . <=. if one is scalar. then the elements of z are z(i. else . Alternatively. . vector or matrices. Logical operators can be used to access elements of a vector or matrix. . Logical operators.j)=(x(i. z=(x<y).Chapter 9 Logical Operators and Find Logical operators are useful when writing batch ﬁles or custom functions. == . <.. For instance. allow for complex choices to be compactly expressed. Suppose z=x < y: y Scalar x Matrix Scalar Any z =x <y Any z i j = xi j < y Matrix Any z i j = x < yi j Same Dimensions z i j = x i j < yi j Logical operators are used in portions of programs known as ﬂow control such as if . For instance. ∼= The core logical operators are > >= < <= == ∼= Greater than Greater than or equal to Less than Less then or equal to Equal to Not equal to Logical operators can be used on scalars.1 >. when combined with ﬂow control. suppose z = x L y where L is one of the logical operators above such as < of ==. It is important to remember that vector or matrix logical operations return vector or matrix output and that ﬂow control blocks require scalar logical expressions. All comparisons are done element-byelement and return either 1 (logical true) or 0 (logical false). will be a matrix of the same size as x and y composed of 0s and 1s.j)<y). . suppose x and y are matrices. 9.

>> y = [1 1]. Logical values and regular numbers are treated differently. if # is not a number but a logical value. Suppose x and y are logical variables (1s or 0s). Since the elements of x are indexed 1.. >> x(y) ans = 1 2 >> y = logical([1 0 1 0]). Logical indices behave like a series of light switches indicating which elements to select: 1 for on (selected) and 0 for off (not selected). and deﬁne z=x \& y: y Scalar x Matrix Scalar Any z = x &y Any z i j = x i j &y Matrix Any z i j = x &y i j Same Dimensions z i j = x i j &y i j 9. a logical value is required.. >> x(y) ans = 1 1 >> y = logical([1 1]). If used on a scalar and a matrix.2. | (OR) and ∼ (NOT) Logical expressions can be combined using three logical devices.2 & (AND). Aside from the different level of precedence. consider the following block of code . an attempt to retrieve x(0) will return an error. >> x(y) ans = 1 3 Using logical indexing produces indices which are interpreted as indicator variables when deciding what to return. Logical indices are interpreted as indicator functions. As previously demonstrated.56 Logical Operators and Find 9. & AND OR NOT | ∼ Recall that ∼ (NOT) has higher precedence than & (AND) and | (OR). . In certain situations. . However. the effect is the same as calling the logical device on the scalar and each element of the matrix. the elements of a matrix x can be accessed by x(#) where # can be a vector of indices. this behavior changes. One such example is in indexing an array. these operators follow the same rules as other logical operators. For another example. the dimensions must be the same.3 logical The command logical is use to convert non-logical elements to logical. Consider the behavior in the following code: >> x = [1 2 3 4]. If used on two matrices. Logical elements only take up 1 byte of memory (The smallest unit of memory MATLAB can address) while regular numbers require 8 bytes.

ans = 0 1 1 1 9. returns 1 if all elements of the column are logical true and 0 otherwise. all returns logical(1) if all logical elements in a vector are 1. although a warning is generated if the values differ from 0 or 1.4 all and any The commands all and any take logical data input and are self descriptive. 3 4]. If all is called on a matrix of logical elements. if called on a matrix. >> x = [1 2 3 4] x = 1 2 3 4 >> y = x<=2 y = 1 1 0 0 >> all(y) ans = 0 >> any(y) ans = 1 >> x = [1 2 . returning logical true if any element of that column is true. For example >> x=[0 1 2 3] x = 0 1 2 3 >> logical(x) Warning: Values other than 0 or 1 converted to logical 1. any operates column-by-column. it works column-bycolumn. Again.9. any returns logical(1) if any element of a vector is logical true. >> y = x<=2. x = 1 2 3 4 >> y = x<=3 y = 1 1 1 0 >> all(y) . >> x(y) ans = 1 2 >> y ans = 1 1 0 0 Note: logical turns any non-zero value into logical true (1).4 all and any 57 >> x = [1 2 3 4].

>> y = x<=3 y = 1 1 ans = 1 2 3 >> [i. >> x = [1 2 3 4].58 Logical Operators and Find ans = 1 0 >> any(y) ans = 1 1 9. These functions all begin with is. There are two primary ways to call ﬁnd.6 is* A number of special purpose logical tests are provided to determine if a matrix has special characteristics..numel(x)) while [i. >> y = x<=2 y = 1 1 0 0 >> find(y) ans = 1 2 >> x = [1 2 ..2.5 find find is an useful function for working with multiple data series. . Some operate element-by-element and produce a matrix of the same dimension as the input matrix while other produce only scalars.j] = find(y) i = 1 2 1 j = 1 1 2 1 0 >> find(y) 9. 3 4]. . indices = find (x < y) will return indices (1. .j] = find (x < y) will return pairs of matrix indices what correspond to the places where x<y. but it takes logical inputs and returns matrix indices where the logical statement is true. find is not logical itself.

7 Exercises 59 1 if NaN element-by-element isinf 1 if Inf element-by-element isfinite 1 if not Inf element-by-element isreal 1 if not complex valued. 3. For both series. . For more details.e. count the number of negative returns in both the S&P 500 and ExxonMobil. What is the correlation when at least 1 of the returns is negative? 5. isnan >> x=[4 pi Inf Inf/Inf] x = 4. What is the relationship between all and any. scalar There are a number of other special purpose is* expressions. Construct an indicator variable that takes the value of 1 when both returns are negative. What is the average return conditional on falling into this range for both returns. Using the data ﬁle created in Chapter 3. 2.1416 Inf NaN Note: isnan(x)+isinf(x)+isfinite(x) always equals 1. How does this compare to the correlation of all returns? 4. scalar ischar 1 if input is a character array scalar isempty 1 if empty scalar isequal 1 if all elements are equal scalar islogical 1 if input is a logical matrix scalar isscalar 1 if scalar scalar isvector 1 if input is a vector (1 ×K of K × 1).7 Exercises 1. Write down a logical expression that allows one or the other to be avoided (i. Compute the correlation of the returns conditional on this indicator variable.0000 >> isnan(x) ans = 0 >> isinf(x) ans = 0 ans = 1 1 0 0 0 1 0 >> isfinite(x) 0 0 1 3. implying any element falls into one (and only one) of these categories. create an indicator variable that takes the value 1 is the return is larger than 2 standard deviations or smaller than -2 standard deviations. search for is* in the help ﬁle. 9. write myany = ??? and myall = ????).9.

60 Logical Operators and Find .

. . . else blocks always begin with an if statement immediately followed by a scalar logi- cal expression and must be terminated with end. . j < 3 However. . Logical variables have another important use: ﬂow control. otherwise.. . . . selecting elements from a matrix. . elseif. . else if . . \lstinlineelse! block is if logical1 Code to run if logical1 true elseif elseif . . Two ﬂow control structures are available: if . . elseif . else Code to run if all previous logicals are false end logical2 logical_3 Code to run if logical2 true and logical1 false Code to run if logical3 true and logical j false. . The generic form of an if .. . . 10. else and switch . if logical Code to run if logical true end or if logical Code to run if logical true else Code to run if logical false end . . .Chapter 10 Flow Control The previous chapter explored one use of logical variables.1 if . Flow control allows different code to be executed depending on whether certain conditions are met. case . elseif and else are optional and can always be replicated using nested if statements at the expense of more complex logic. . elseif . . . . elseif . simpler forms are more common..

. . . . The basic structure of this block is to ﬁnd some variable whose value can be used to choose a piece of code to execute (the switch variable). Do not feel obligated to use these if not comfortable in their application. end >> x x = 4 and x = 5. . else x=x-1. . . However. . . else x=2*x.otherwise switch. end >> x x = 10 These examples have all used simple logical expressions.case. If no cases are matched (otherwise). any scalar logical expressions. . However. . The generic form of an switch . .otherwise blocks allow for more advanced ﬂow control although they can be completely replicated using only if . . a default block of code is executed. case . if x<5 x=x+1. can be used in if . a particular piece of code will be executed. . 10. otherwise block is switch variable case value1 Code to run if variable=value1 true case value2 Code to run if variable=value2 true case value3 Code to run if variable=value3 true . case . else blocks. .62 Flow Control Note: Remember that all logicals must be scalar logical values. .case. . at most one block is matched. . elseif . . such as (x<0 || x>1) \&\& (y<0 || y>1) or isinf(x) || isnan(x). otherwise block. . A few simple examples x = 5. . . elseif x>5 x=x-1. .2 switch. else ﬂow control blocks. otherwise can safely be omitted and if not present no code is run if none of the cases are matched. Matching a case causes that code block to execute then the program continues running on the next line after the switch . if x<5 x=x+1. Depending on the value of this variable (its case). elseif . .

otherwise example: x=5. case . . .case2 .. case {1. if the logical expressions in the if . . else blocks. . elseif . .. otherwise x=0. otherwise Code to run if variable = value j ∀ j end Note: There is an equivalence between switch . case 6 x=x-2. .2. switch x case {4} x=x+1. . otherwise blocks also differ from standard C behavior since only one case can be matched per block.case. . case . .. . . . . . The switch . else block contain inequalities.otherwise 63 . . . switch .2. otherwise and if . . end >> x x = 10 x = 4. . }. otherwise block. elseif . .2 switch. . end >> x x = 10 cases can include multiple values for the switch variable using the notation case {case1 . switch x case 4 x=x+1. . otherwise x=0. . case 5 x=2*x. variables must be created prior to using a switch . . .10. case . .5} x=2*x. switch x case {4} x=x+1.. x=5. For example. .. A simple switch . . otherwise block is exited after the ﬁrst match and the program resumes with the next line after the block. . .5} x=2*x. However. . . . case {1. . . case . . case . otherwise .

. Construct a variable which takes the values 1. . . . or they have different signs using an if . case . otherwise block. both are negative. Write a code block that would take a different path depending on whether the returns on two series are simultaneously positive. else block. 2 or 3 depending on whether the returns in exercise 1 are both positive (1).64 Flow Control x=0. end >> x x = 5 10. .3 Exercises 1. . . both negative (2) or different signs (3). . elseif . Repeat exercise 1 using a switch . 2. .

5.g. possible. including non-integer and/or negative values. vector is a vector of data. . It can be an existing vector or it can be generated on the ﬂy using linspace or a:b:c syntax (e.end and while. end . . They are nearly equivalent when break is used.end.50) count=count+i. for i=1:100 count=count+i. although it is generally preferable to use a while loop than a for loop and a break statement.Chapter 11 Loops Loops make many problems. One subtle aspect of loops is that the iterator can contain any vector data. All for loops can be expressed as while loops although the opposite is not true. for i=linspace(0. particularly when combined with ﬂow control blocks. 11. x=linspace(-20. The generic structure of a for loop is for iterator=vector Code to run end iterator is the variable that the loop will iterating over. Consider these three examples: count=0. 1:10). Two types of loop blocks are available: for.500). for i=x count=count+i. i is a common name for an iterator. .1 for for loops begin with for iterator=vector and end with end.20. . simple and in many cases. for blocks iterate over a predetermined set of values and while blocks loop as long as some logical expression is satisﬁed. end count=0. For example. end count=0.

j)=i+j. .2) if i<j matrix(i. The second loops over the values produced by the function linspace which creates 50 uniform points between 0 and 5.10). for i=1:size(matrix.66 Loops The ﬁrst loop will iterate over i = 1. . for i=1:length(returns) if returns(i)<0 count=count+1. vector(2). end end and can contain ﬂow control variables: returns=randn(100.e. . end end One particularly useful construct is to loop over the length of a vector. . which allows each element to be modiﬁed one at a time. . these ideas can be combined to produce nested loops with ﬂow control. vector(1).20. x=[1 3 4 -9 -2 7 13 -1 0].500). inclusive. matrix=zeros(10.).1). Loops can also be nested: count=0. for i=x count=count+i.1) for j=1:size(matrix. 100. trend=zeros(100. Loops can also iterate over decreasing sequences: count=0. x=-1*linspace(0. end Finally. else . a vector constructed from a call to linspace. for i=x count=count+i. The ﬁnal loops over x. for i=1:10 for j=1:10 count=count+j. . count=0. end The key to understanding for loop behavior is that for always iterates over the elements of vector in the order they are presented (i.1). for i=1:length(trend) trend(i)=i.. end or vector with no order: count=0. 2.

for i=1:size(matrix.. end else for j=1:size(matrix. while loops are commonly used when a loop should only stop if a certain condition is met. The generic structure of a while loop is .j)=i-j. such as the change in some parameter is small. end end end or loops containing nested loops that are executed based on a ﬂow control statement.11. for i=1:100.2 while 67 matrix(i. i i=2*i. end end end Note: The iterator variable must NOT be modiﬁed inside the for loop. 11.j)=i-j.. which can lead to unpredictable results if i is used inside the loop.1) if (i/2)==floor(i/2) for j=1:size(matrix.10). i end Produces the output i = 1 i = 2 i = 2 i = 4 i = 3 i = 6 . For instance.2 while while loops are useful when the number of iterations needed depends on the outcome of the loop contents.2) matrix(i.2) matrix(i. Changing the iterator can produce undesirable results. matrix=zeros(10.j)=i+j.

there are situations where no for loop equivalent exists. The simplest while loops are drop-in replacements for for loops: count=0. i=i+1. break can also be used to end a while loop before running the code inside the loop. the loop will continue indeﬁnitely (hit CTRL+C to break an interminable loop).3 break break can be used to terminal a for loop and. i=1. the number of iterations required is not known in advance and since randn is a standard normal pseudo-random number. However. for i=1:10 count=count+i. while abs(mu) > . end In the block above. for loops can be constructed to behave similarly to while loops.0001 mu=(mu+randn)/index. end while loops should generally be avoided when for loops will do. as a result. it may take many iterations until this criteria is met. Consider this slightly strange loop: . end which produces the same results as count=0. mu=1.68 Loops while logical Code to run Update to logical inputs end Two things are crucial when using a while loop: ﬁrst. for iterator = vector Code to run if logical break end end The only difference between this loop and a standard while loop is that the while loop could potentially run for more iterations and iterator. index=index+1. while i<=10 count=count+i. If they are not. the logical expression should evaluate to true when the loop begins (or the loop will be ignored) and second the inputs to the logical expression must be updated inside the loop. index=1. 11. Any ﬁnite for loop cannot be guaranteed to meet the criteria.

The process of an ARMA(2.2) where εt are independent standard normal innovations. Simulate 1000 observations from an ARMA(2.2) is given by y t = φ1 y t −1 + φ2 y t −2 + θ1 εt −1 + θ2 εt −2 + εt Use the values φ1 = 1. if x < 0 break end y = sqrt(x). θ1 = . The effect of continue is best seen through a block of code.. φ2 = −. that will run indeﬁnitely. More importantly. While continue can always be avoided using if. .5 Exercises 1. even when simulating a short series. the break command will stop the loop if some condition is met. the break will prevent the code after it from being run.else blocks. which is useful if the operations after the break will create errors if the logical condition is not true. . i = 7 i = 9 demonstrating that continue is forcing the loop to the next iteration whenever i is even (and (i/2)== floor(i/2) evaluates to logical true). if left alone. This process is fairly persistent. when used inside a loop. always simulate more data then needed and throw away the ﬁrst block of observations to avoid start-up biases. has the effect of advancing the loop to the next iteration and skipping any remaining code in the body of the loop.4 and θ2 = . Note: When simulating a process. for i=1:10 if (i/2)==floor(i/2) continue end i end which produces output . .4. its use can make result in tidier code. .. 11.. always compute extra data points to throw away.8.11. end The use of while 1 will produce a loop. at least 100 extra observations should be computed..4 continue continue.8. However. 11. As a rule.4 continue 69 while 1 x = randn.

α = 0. Verify it is working by taking the absolute value of the difference between the ﬁnal value and the value produced by norminv.1) process is given by y t = εt h t h t = ω + αεt −1 + γεt −1 I [εt −1 <0] + β h t −1 Use the values ω = 0. write a bit of code that will do a bisection search to invert a normal CDF. Using a while loop.1.05 and β = 0. 6.4 and λ = 0. Simulate a GJR-GARCH(1.1.9. Test out the loop using by ﬁnding the inverse CDF of 0. This problem requires normcdf. Hint: Some form of logical expression is needed in the loop.05. 5.03.1) process where εt are independent standard normal innovations. I [εt −1 <0] is an indicator variable that takes the value 1 if the expression inside the [ ] is true. -3 and pi. θ1 = 0.05. Simulate a ARMA(1.1) process where εt are independent standard normal innovations. A GARCH(1.1)-GJR-GARCH(1. α = 0. 4.9. Hint: keep track of the upper and lower bounds of the random variable value and use ﬂow control. 3.02 γ = 0. Simulate a GARCH(1.1) process is given by y t = εt ht h t = ω + αεt −1 + β h t −1 Use the values ω = 0. only keeping the sub interval with the target in it.70 Loops 2.07 and β = 0. y t = φ1 y t −1 + θ1 εt −1 h t −1 + λh t + εt ht h t = ω + αεt −1 + γεt −1 I [εt −1 <0] + β h t −1 Use the values from Exercise 3 for the GJR-GARCH model and use the φ1 = −0. A GJRGARCH(1. A bisection search cuts the interval in half repeatedly.1)-in-mean process. .

.format1 . These four are the most important support functions.x2.9).y2. • legend labels the various elements on a graph. legend takes as many strings as unique plot elements. the most straight forward is plot(x1. Standard usage is title(’Figure Title’). 12.1 Support Functions All plotting functions have a set of support functions which are useful for providing labels for various portions of the plot or making adjustments to the range. Like most commands. . Standard usage is legend(’Series 1’.Chapter 12 Graphics Extensive plotting facilities capable of producing a virtually limitless range of graphical data representations are available. . • title places a title at the top of a ﬁgure. The speciﬁc behavior of legend depends on the type of plot and the order of the data. axis can also be used to tighten the axes to include only the minimum space required to express the data using the command axis tight.’Series 2’) where the number of series is ﬁgure dependent. Remember to fully label plots so others can clearly tell which series are being plotted and the units of the plot. Standard usage is xlabel(’X Data Name’).y1. • xlabel. To retrieve the current axis limits.) . it can be used many ways. The axis can be changed by calling axis([xlow xhigh ylow yhigh (zlow) (zhigh)]) where the z-variables are only allowed if the ﬁgure is 3-D. 12.format2 }. However..2 plot plot is the most basic plotting command. enter AX = axis(). This chapter will emphasize the basics of the most useful graphing tools. ylabel and zlabel produce text labels on the x . • axis can be used to both get the axis limits and set the axis limits. but there are many additional functions available to tweak ﬁgures (see section 12. AX will be a row vector of the form [xlow xhigh ylow yhigh (zlow) (zhigh)] where zlow and zhigh are only included if the ﬁgure is 3-D. y and z –if the plot is 3-D – axes respectively.

y2 = x.y3. y3 = 1-4*abs(x-0. . If no format string is provided. color can be any of b g r c m y k shape can be any of o x + * s d v ∧ blue green red cyan magenta yellow black < > p h and linespec can be any of circle x-mark plus star square diamond triangle (down) triangle (up) triangle (left) triangle (right) pentagram hexagram : -.’kp--’) will produce the plot in ﬁgure 12.5). -(none) solid dotted dashdot dashed no line The three arguments are combined to produce a format string. Always use physical characteristics to distinguish multiple series – either different line types or different markers. For instance.5).x. x = linspace(0. For instance ’gs-’ will produce a green solid line with squares at every data point while ’r+ ’ will produce a set of red + symbols at every data point (note that the string is r-plus-space). use the format string ’g:’.72 Graphics where xi and yi are vector of the same size and formati is a format string of the form color shape linespec. to produce a green dotted line with no symbol. Calling plot(x.1. or both. an automatic color scheme will be used with marker-less solid lines.^2. y1 = 1-2*abs(x-0.x.1.’rs:’.’. Suppose the following x and y data were created.100). Arguments which are not needed can be left out. A line’s color information is lost when documents printed are in black and white.y2.’bo-.y1.

2.5).’f(x)=x’. plot will draw each column of y as if it was a separate series and plot(y) is equivalent to plot(1:length(y(:. . All plots should be clearly labeled.x.y2.’f(x)=1-4*abs(x-0.2). gives the ﬁgure a title. The results of running the code along with the plot command above can be seen in ﬁgure 12.8 0.x2. The lines were plotted with the command plot(x.format2 .9 1 Figure 12. ylabel(’f(x)’).3 0.z2. and provides a legend.-’). All arguments are the same and the generic form is plot3(x1.7 0.’kp.5 0.1)).6 0.1 0. . y(:.x. 12. .y) when y is a vector. plot(y) will plot the data in vector y against a simple series which labels each observation 1. . . y(:. One ﬁnal method for calling plot is worth mentioning.^2’). 1:length(y(:.9 0.’rs:’.3 plot3 73 1 0. plot(y) is equivalent to plot(1:length(y).3 plot3 plot3 is behaves similarly to plot but plots a series against two other series in a 3-dimensional space.1: Simple plot of three lines. .’.2 0.).’bo-.7 0. xlabel(’x’).5 0.format1 . length(y).2 0.4 0.5|’. If y is a matrix.y2.y3.6 0.4 0. legend(’f(x)=1-|x-0.z1. . title(’Plot of three series’)..) .1 0 0 0. The following code labels the axes.8 0.2.12.2)).1).y1.y1..3 0. .

8*pi. zlabel(’z’).6 f(x) 0.7 0. y=cos(y).5 x 0.2 0. y=linspace(0.2 0.2: Labeled plot of three lines. Clearly label axes and provide a title and legend so readers can easily comprehend the contents of a ﬁgure.N).1.9 1 Figure 12.6 0.y.74 Graphics Plot of three series 1 f(x)=1−|x−0.2 0.N). x=sin(x). plot3(x.8 0.’rs:’).5| f(x)=x 0. The following code block demonstrates the use of plot3. ylabel(’y’).3 0.8*pi.8 0. title(’Spiral’). x=linspace(0.4 0.9 f(x)=1−4*abs(x−0.5 0.z. xlabel(’x’).1 0 0 0. .1 0. z=linspace(0.N).7 0.3 0.5). legend(’Spiraling Line’) The results of this block of code can be seen in ﬁgure 12.4 0.3. figure(2) N=200.

5.4 scatter scatter.’rs:’).4 scatter 75 Spiral Spiraling Line 1 0. figure(4) x=randn(1000.6 z 0.4. The following code produces a scatter plot of 1000 pseudo-random numbers from a normal distribution.y. is self descriptive.2).5 0.5 1 Figure 12.1 0 1 0.3 0. Simple example of handle graphics are included at the end of this chapter.x(:.’rs’) xlabel(’x’) ylabel(’y’) legend(’Data point’) title(’Scatter plot of correlated normal random variables’) .. 12. x=x*Sigma^(0.3: 3-D Spiral plot.1).5 x 0. like most graphing functions. The output of this code can be seen in ﬁgure 12..z.7 0.4 0. each with unit variance and correlation of 0.5. It produces a scatter plot of the elements of a vector x against the elements of a vector y .12. This line was plotted by calling plot3(x.9 0. scatter(x(:. Formatting.2).2 0. Consult scatter’s help ﬁle for further information.5 0 0 −0. 3-D lines can be plotted using the plot3 command.5 0.5 y −1 −1 −0.5].8 0. Sigma=[2 .5). such as color or marker shape can only be changed by using handle graphics or by manually editing the plot.

4: Scatter plot.2). All three uses the results from a bivariate normal probability density function.76 Graphics Scatter plot of correlated normal random variables 3 Data point 2 1 0 y −1 −2 −3 −5 −4 −3 −2 −1 x 0 1 2 3 4 Figure 12.5. .x(:. pdf=zeros(N. pdf was created with the following code: N = 100.5 surf The next three graphics tools all plot a matrix of z data against vector of x and y data. was chosen Σ= 2 0..5 0.5 0.N).N). Σ.N).1).3.5 A matrix of pdf values. y = linspace(-2.’rs’). x = linspace(-3.2. the covariance matrix. 12. The PDF of a bivariate normal with mean 0 is given by f X (x ) = − 1 exp(− x Σ−1 x ) 2 2π|Σ| 1 2 1 In this example. This line was plotted by calling scatter(x(:. This plot contains a scatter plot of a bivariate normal random deviations with unit variance and correlation of 0.

12.5 surf

77

Figure 12.5: Surface plot. surf plots a 3-D surface from vectors of x and y data and a matrix of z data. This

surf contains the PDF bivariate of a bivariate normal, and was created using surf(x,y,pdf) where x, y and pdf are deﬁned in the text.

for i=1:length(y) for j=1:length(x) pdf(i,j)=exp(-0.5*[x(j) y(i)]*Sigma^(-1)*[x(j) y(i)]’)/sqrt((2*pi)^2*det(Sigma)); end end

The ﬁrst two lines initialize the x and y values. Since x has a higher variance, it has a larger range. The surf (ﬁgure 12.5) was created by

surf(x,y,pdf) xlabel(’x’) ylabel(’y’) zlabel(’PDF’) title(’Surf of normal PDF’) shading interp

The command shading interp changes how the colors are applied from a discrete grid to a continuous grid. Note: The x and y arguments of surf must match the dimensions of the z argument. If [M,N]=size(z), then length(y) must be M and length(x) must be N. This is true of all 3-D plotting functions that draw matrix data. In the code above, i is the row iterator which corresponds to y and j is the column iterator,

78

Graphics

corresponding to x.

12.6 mesh

mesh produces a graphic similar to surf but with empty space between grid points. Mesh has the advantage

that the hidden side can be seen, potentially revealing more from a single graphic. It also produces much smaller ﬁles which can be important when including multiple graphics in a presentation or report. Using the same bivariate normal setup, the following code produces the mesh plot evidenced in ﬁgure 12.6.

Mesh of normal PDF

0.2 0.18 0.16 0.14 0.12 PDF 0.1 0.08 0.06 0.04 0.02 0 2 1.5 1 0.5 0 −0.5 −1 −1.5 y −2 −3 x −2 −1 0 1 2 3

Figure 12.6: Mesh plot. mesh produce a ﬁgure similar to surf but with gaps between grid points, allowing the backside of a ﬁgure to be seen in a single view. This mesh contains the PDF of a bivariate normal, and was created using mesh(x,y,pdf) where x, y and pdf are deﬁned in the text.

mesh(x,y,pdf) xlabel(’x’) ylabel(’y’) zlabel(’PDF’) title(’Mesh of normal PDF’)

12.7 contour

79

12.7 contour

contour is similar to surf and mesh in that it takes three arguments, x , y and z . contour differs in that it

produces a 2D plot. contour plots, while not as eye-catching as surf or mesh plots, are often better at conveying meaningful information. Contour plots can be either called as contour(x,y,z) or contour(x,y,z,N) where N determines the number of contours drawn. If omitted, the number of contours is automatically determined based on the variance of the z data. The code below and ﬁgure 12.7 demonstrate the use of contour.

Contours of normal PDF 2

1.5

1

0.5

0

y

−0.5

−1

−1.5

−2 −3

−2

−1

0 x

1

2

3

Figure 12.7: Contour plot. A contour plot is a set of slices through a surf plot. This particular contour plot contains iso-probability lines from a bivariate normal distribution with mean 0, variances of 2 and 0.5, and correlation of 0.5.

contour(x,y,pdf); xlabel(’x’) ylabel(’y’) title(’Contours of normal PDF’)

12.8 subplot

Subplots allow for multiple plots to be placed in the same ﬁgure. All calls to subplot must specify three arguments, the number of rows, the number of columns, and which cell to place the graphic. The generic

errorbar(x. explode = [0 1 0 0 0]. and # indicates the cell to place the graphic.5 2].80 Graphics form is subplot(M .4).8 demonstrates how different data visualizations may be used in every cell. In the simplest case. For instance. Y = cool(7). if is often useful to change the thickness of a line in order to improve its . 12. where M is the number of rows. ’’Grouped’’’) axis tight subplot(2.2. the #’s would be 1 2 3 4 5 6 A call to subplot should be immediately followed by some plotting function.#). this would be a call to plot.e) title(’errorbar’) axis tight Note: The graphics code in each subplot was taken from the function’s help ﬁle (see doc function). These also show a few of the available graphics function that are not described in these notes.’detached’) title(’Detached’) title(’bar3. pie(x.2. x = [5 3 0. y = sin(x).2. However.N .5 2.#). The code below and output in ﬁgure 12. x = 1:10.2.3) bar3(Y. in a call to subplot(3.’grouped’) title(’bar3.explode) colormap jet title(’pie function’) axis tight subplot(2. The help system is comprehensive and most functions are illustrated with example code.y. Cells in a subplot are counted across then down For instance. these function are not ﬂexible enough to express all of the options available. e = std(y)*ones(size(x)).9 Advanced Graphics While the standard graphics functions are powerful. subplot(2. any graphic function can be used in a subplot. N is the number of columns.2).1).2. ’’Detached’’’) axis tight subplot(2. bar3(Y.

5 19% 0 1 2 3 4% 4 5 6 7 23% 1 2 3 bar3. the lower left contains a call to bar3 specifying the options ’detached’ and the lower right contains the results to a call to errorbar. which will be referred to as “pointand-click”. to be selected. These include color. is known as handle graphics.4 0. The second. involves manually editing the plot in the ﬁgure window. A number of buttons are available along the top edge of a plot. search for Editing Plots in the help browser.5 1.2 0 0 1 2 3 4 5 6 7 −1. (1) in ﬁgure 12. Two mechanisms are provided to add elements to a plot.12. Handle graphics provides a mechanism to programmatically change anything about a graph.5 errorbar 6 8 10 Figure 12. The ﬁrst. ’Grouped’ 1 0.8 0. ’Detached’ 38% 0. and marker (3). . line width.5 1 0.9.9 Advanced Graphics 81 pie function 15% 1 bar3. Point-and-click The simplest method to improve plots is to use the editing facilities of the ﬁgure windows directly. The upper left contains a call to pie. appearance or to add an arrow to highlight a particular feature of a graph. Double-clicking on a line will bring up a Property Editor (2) dialog which contains elements of the selected item that can be changed. For more information in editing plots. the upper right contains a call to bar3 specifying the option ’grouped’. and more general of the two. such as a line. Clicking on the arrow will highlight it and allow any element.6 0. This particular subplot contains three different types of graphics with two variants on the 3-D bar.5 2 4 −1 −0. Subplots allow for more than one graphic to be included in a ﬁgure. One the of these is an arrow.8: Subplot example.

g. = cumsum(e). This will bring up the Property Editor (2) where the item speciﬁc properties can be changed (3). Most features of a plot can be editing using the interactive editing tools of a ﬁgure window.2).9: Point-and-click editing. Anything that can be accomplished through manual editing of a plot can be accomplished by using handle graphics.82 Graphics Figure 12. Alternatively. Handle Graphics The graphics system is fully programmable. any text label). the axes. such as colors or line widths. Every graphical element is assigned a handle. e y = randn(100. the interactive editing features can be enabled by selecting Edit>Figure Properties. the line. Interactive editing can be started by ﬁrst selecting the arrow icon along the top of the ﬁgure (1). then clicking on the element to be edited (e. they can be used to create spectacularly complex data visualizations. The use of handle graphics will be illustrated through an example. Once familiar with handle graphics. . The example will illustrate the use of handle graphics by showing both before and after plots using subplot. The handle contains everything there is to know about the particular graphic.

’demi’) set(xl.’Random Walk 2’) title(’Two Random Walks’) xlabel(’Day’) ylabel(’Level’) subplot(2.1.1.3.’FontWeight’. Using the ExxonMobil and S&P 500 data (see the Chapter 3 exercises).’Bookman Old Style’.’FontSize’. If using the point-and-click editing method.’Bookman Old Style’.10 Exercises 83 subplot(2.’Parent’).2).’Location’. For more on handle graphics. produce a 2 × 2 subplot containing: • A scatter plot of the two series • Two histograms of the series • One plot of the two series against the dates.’Bookman Old Style’. If handle graphics have been used.’) set(t.10 Exercises 1.14’. = title(’Two Random Walks’) xl = xlabel(’Day’) yl = ylabel(’Level’) set(h(1).’LineWidth’. please consult the Handle Graphics Properties in the help ﬁle.14’.3.’Southwest’). legend(’Random Walk 1’.’LineStyle’.’Color’.[1 0 0].’LineStyle’. it is only necessary to change the data and the re-run the m-ﬁle.’FontWeight’. plot(y).’Color’.’FontName’.’FontSize’.’Bookman Old Style’. Generate two random walks using a loop and randn. y = sin(x).’FontName’. Plot these two on a ﬁgure and provide all of the necessary labels.’Bookman Old Style’. = legend(’Random Walk 1’.6 0].’FontName’.’FontWeight’. Generate 1000 draws from a normal.14’.’LineWidth’. z = x*y. The advantage of handle graphics is only apparent when a ﬁgure needs to be updated or redrawn.’:’) set(h(2).12. Generate a 3-D plot from x = linspace(0. 3.’FontWeight’. set(parent. title the ﬁgure and provide a legend.’FontSize’.’Random Walk 2’.’FontWeight’.’demi’) set(l.14’. 4.300).’FontSize’. Plot a histogram with 50 bins of the data. . any change in the data or model required manually reapplying the edits. Change the axis labels to text using datetick.’FontSize’.’demi’) parent = get(h(1).’FontName’.’demi’) set(yl. 2.10*pi. Label all axes.’FontName’.’demi’) Most modiﬁcation that can be made using handle graphics can be implemented using the point-andclick editing method previously outlined.14’.’-. 12.[1 .1). h l t = plot(y).

It is worth nothing that all of these changes evidenced in the bottom subplot can be reproduces using the point-and-click method.84 Graphics Two Random Walks 5 Random Walk 1 Random Walk 2 0 −5 Level −10 −15 −20 0 10 20 30 40 50 Day 60 70 80 90 100 Two Random Walks 5 0 Level −5 −10 −15 −20 0 Random Walk 1 Random Walk 2 10 20 30 40 50 Day 60 70 80 90 100 Figure 12. The top subplot is a standard call to plot while the bottom highlight some of the possibilities when using handle graphics. .10: Handle graphics.

Save As (1 in ﬁgure 13. On the ﬁgure. report or project. . in the ﬁle menu of a ﬁgure (1). EPS ﬁle for LTEX(2 in ﬁgure 13. . Figure 13. A select the desired format (TIFF for Microsoft Ofﬁce uses.2) and save.2 will appear.1). To export a ﬁgure. it must be exported to be included in an assignment. click File. enter a ﬁle name (1 in ﬁgure 13. Figures 13.1: Steps to export a ﬁgure. click Save As.1 and 13.2 contain representations of the steps needed to export from a ﬁgure box. . Exporting is straight forward. The dialog in ﬁgure 13. In the Save as type box.Chapter 13 Exporting Plots Once a plot has been ﬁnalized.2)).

1. To export a ﬁgure. fig = figure(2). plot(x.5|’). x = linspace(0.5). plot(x. y = 1-abs(x-0.’r’) . set(fig.100). it may be necessary to alter the shape of the ﬁgure’s window. title(’Roof-top plot’). The following code will the three ﬁgures.4 and 13. y = 1-abs(x-0. Select TIFF image if using Microsoft Ofﬁce or EPS File (Encapsulated Postscript) if using LTEX.5|’). enter a ﬁle name and use the drop-down box to select a ﬁle A type.100).5 poorly scaled.’r’) xlabel(’x’).2: Save as dialog.5).1. Exported ﬁgures are What-You-See-Is-What-You-Get (WYSIWYG).[445 -212 957 764]). x = linspace(0.86 Exporting Plots Figure 13.y. If the exported ﬁgure does not appear as desired. ylabel(’y=1-|x-0. legend(’f(x)=1-|x-0. Figure 13.y.’Position’.3 contains an example of a ﬁgure with reasonable proportions while the axes in Figures 13. fig = figure(1).

9 0. x = linspace(0.5|’).y.’r’) xlabel(’x’).[1 1 1]. set(fig.7 0.’Color’. plot(x. pdf for portable document format (LTEX) or tiff for Tiff (Microsoft Ofﬁce).13.5 0 0.[ 445 216 957 336]).5|’).100).’Position’.5|’).4 0. The axes in this ﬁgure are appropriately scaled. legend(’f(x)=1-|x-0.85 0. Tiff images are static and become blurry when scaled.5| 0. title(’Roof-top plot’).5|’).8 y=1−|x−0.’InvertHardcopy’.55 0. ylabel(’y=1-|x-0.8 0.65 0.5 x 0.1 print Figures can also be exported programmatically using the print command. 13. Note: It is necessary to call set(gcf.6 0.5). Figures exported in EPS or PDF formats are vector images and scale both up and down well.’off’) before print to remove . y = 1-abs(x-0. -212 461 764]).75 0.7 0.2 0. xlabel(’x’). set(fig.6 0. legend(’f(x)=1-|x-0.95 0.9 1 Figure 13.1 print 87 Roof−top plot 1 f(x)=1−|x−0.[ 445 fig = figure(3).’Position’. ylabel(’y=1-|x-0.3 0.1 0.5| 0.1. title(’Roof-top plot’). The basic structure of the comA mand is print -dformat ﬁlename where format is epsc2 for color encapsulated postscript (LTEXor Microsoft A Ofﬁce).3: Exporting ﬁgures is What-You-See-Is-What-You-Get.

The axes in this ﬁgure are poorly scaled and the height is too large for the width.9 0.55 0.75 0.6 0.8 0.6 0.9 1 Figure 13.85 0. Roof−top plot 1 f(x)=1−|x−0.4: Exporting ﬁgures is What-You-See-Is-What-You-Get.88 Exporting Plots Roof−top plot 1 f(x)=1−|x−0.95 0.7 0.4 x 0.8 1 Figure 13.1 0.6 0.9 y=1−|x−0.7 0.5 0 0.8 y=1−|x−0.8 0.3 0.5| 0.2 0.5 x 0.5| 0. The axes in this ﬁgure are poorly scaled and the width is too large for the height.6 0. the gray border surrounding the ﬁgure.5: Exporting ﬁgures is What-You-See-Is-What-You-Get. fig = figure(1).4 0.5 0 0.7 0.2 0.65 0.5| 0. .5| 0.

13.2 Exercises

89

x = linspace(0,1,100); y = 1-abs(x-0.5); plot(x,y,’r’) xlabel(’x’); ylabel(’y=1-|x-0.5|’); title(’Roof-top plot’); legend(’f(x)=1-|x-0.5|’); set(fig,’Position’,[445 -212 957 764]); set(gcf,’Color’,[1 1 1],’InvertHardcopy’,’off’) print -depsc2 ExportedFigure.eps print -dpdf ExportedFigure.pdf print -dtiff ExportedFigure.tiff

13.2

Exercises

1. Export the plot from exercise 1 of the previous chapter as a TIFF and an EPS. View the ﬁles created outside of MATLAB. 2. Use page setup to change the orientation and dimensions as described in this chapter. Re-export the ﬁgure as both a TIFF and EPS (using different names) and compare the new images to the old versions.

90

Exporting Plots

Chapter 14

Custom Functions

In addition to writing batch ﬁles and calling predeﬁned functions, custom functions can be written to perform repeated tasks or to use as the objective of an optimization routine. All functions must begin with the line of the form

function [out1, out2, . . .] = functionname(in1,in2,. . .)

where out1, out2, . . . are variables the function returns to the command window, functionname is the name of the function (which should be unique and not a reserved word) and in1, in2, . . . are input variables. Obviously functions can take multiple inputs sand return multiple outputs. To begin, consider this simple function:

function y = func1(x) x = x + 1; y = x;

This function, which is not particularly well written1 , takes one input and returns one output, incrementing the input variable (whether a scalar, vector or matrix) by one. Functions have a few important differences relative to standard m-ﬁle scripts. • Functions operate on a copy of the original data. Thus, the same variable names can be used inside and outside of a function without risking any data.2 • Any variables created when the function is running, or any copies of variables made for the function, are lost when the function completes. In the function above, this means that only the value of y is returned and everything else is lost. Speciﬁcally changes in x do not persist. For example, suppose the following was entered

>> x = 1; >> y = 1; >> z = func1(x); >> x

It has no comments and superﬂuous commands. The function should only contain y = x +1; and a comment that describes the function’s purpose. 2 MATLAB uses a copy-on-change model where data is only copied if modiﬁed. If unmodiﬁed, variables passed to functions behave as if passed by reference.

1

For instance. Functions with multiple inputs and outputs can also be constructed. comments in custom functions are made using the % symbol. how many output were requested (nargout). the ﬁrst continuous block of comments is displayed in the command window. in the function func function y = func(x) % This |function| returns % the value of the input squared. respectively) and that allow for early termination of the function (return). the values of x and y in the workspace do not change when the function is called. z2] = func2(x . A simple example is given by function [xpy.y) z1 = 2 z2 = 0 There are a number of advanced function speciﬁc variables available to determine environmental parameters such as how many input variables were provided to the function (nargin). that allow variable numbers of input and outputs (varargin and varargout. However.1 Comments Like batch m-ﬁles. despite the function using variables named x and y. y) z1 = 2 >> [z1. Whenever help function is entered in the command window. For example. This function takes two inputs and returns two outputs. comments have an additional purpose in custom functions. >> y = 1. However. 14.y) xpy = x + y. This course can be completed without using any of these.92 Custom Functions x = 1 >> y y = 1 >> z z = 2 Thus. It is important to note that despite the two outputs of this function. xmy = x . % The next block of comments will not be returned when % ’help func’ is entered in the Command Window . xmy] = func2(x. >> z1 = func2(x. they are available if needed in other research. consider the following use of this function >> x = 1. it does not need to be called using both.y.

y) xpy = x + y. .2 Debugging Since the data modiﬁed in the function is not available when the function is run. help func returns >> help func This function returns the value of the input squared. %function [xpy. Once ﬁnished inspecting the variables. xmy = x . use disp.y. The ﬁrst of these methods is often the easiest. variables inside the function are treated as if they were script variables. y = 2. • Leave off . Entering whos will list two variables. they should be included both to improve readability of the function and to assist others if the function is shared. Alternatively. enter return to continue the execution of the function.y. The third options is the most advanced. When in keyboard mode. the original two and xpy and xmy.^2. xmy] = func3(x. when calling it as a script. 14. keyboard Calling this function will result in an immediate keyboard session (note the K>>). debugging can be difﬁcult. Often the output window becomes ﬁlled with numbers and locate the problematic code may be difﬁcult. function [xpy. Initial comments usually contain the possible combinations of input and output arguments as well as a description of the function. Consider a script version of the function above. When a function has been debugged. However. The second method can be useful although clumsy. y=x. • Use keyboard and return to interrupt the function to inspect the values. Entering whos will now list four variables. either comment out or remove the keyboard commands. When in this situation. x = 1. A simple example of keyboard can be adapted to the function above. There are three basic strategies to debug a function: • Write the “function” as a script and then convert it to a proper function. While comments are optional. variables can be examined as they change. the usual >> prompt changes to a K>>. xmy = x .2 Debugging 93 % This line does the actual work. When return is entered.14.y) keyboard xpy = x + y.2). as needed to write out the value of variables to the command window. Running this script would be equivalent to calling the function func2(1. xmy] = func2(x. Adding keyboard to a function interrupts the function at the location of keyboard and returns control to the command window. a second keyboard session open. x and y.

skewness(x(:.K)) . . .1)) kurtosis(x(:. the mean and the variance. .1)) skewness(x(:. 4.2)) kurtosis(x(:. kurtosis(x(:. . mean(x(:. .3 Exercises 1. and returns a matrix of summary statistics of the form mean(x(:.K)) . . . std(x(:.2)) skewness(x(:. Write a function called normloglikihood that takes two arguments.1)) mean(x(:. one each for mean. Note: params = [mu sigma2] consists of two elements. 3. skewness and kurtosis. .K)) 2. .2)) .2)) std(x(:. std.94 Custom Functions 14. Rewrite the function so that it outputs 4 vectors. params and data (in that order) and returns the log-likelihood of a vector of data. Write a function summstat that take one input. a T by K matrix. Append to the previous function a second output that returns the score of the log-likelihood (a 2 × 1 vector) evaluated at params.K)) .1)) std(x(:.

15. random number generators and inverse CDFs. *pdf. All common distributions have the complete set of four provided. PDFs. *inv .1 quantile quantile returns the empirical quantile of a vector.Chapter 15 Probability and Statistics Functions The statistics toolbox contains an extensive range of statistical function. length and floor or ceil. 15.2 prctile prctile is identical to quantile except it expects an argument from 0 to 100 rather than an argument between 0 and 1.4 *cdf. including • χ 2 (chi2-) • β (beta-) • Exponential (exp-) • Extreme Value (ev-) • F (f-) . its function is simple and can easily be re- placed using sort. The most valuable code in the statistics toolbox are the CDFs. The Statistic Toolbox implemen- tation is not robust to many empirical realities in ﬁnance such as heteroskedasticity and writing a custom regression function is a useful exercise. 15.3 regress regress performs basic regression and returns key regression statistics. 15. However. *rnd.

It also has a number of useful plotting functions such as pltdens which plots an kernel smooth of an empirical density. also referred to as the MFE toolbox.5 The UCSD_GARCH/MFE Toolbox The UCSD_GARCH toolbox. 15. 2.96 Probability and Statistics Functions • Γ (gam-) • Lognormal (logn-) • Normal (Gaussian) (norm-) • Poisson (poiss-) • Student’s t (t-) • Uniform (unif-) 15. Have a look through the list of functions available. it is free. Download the JPL toolbox and extract its contents. contains many econometric functions written by academics. is a set of functions for making inference on many common problems in ﬁnancial econometrics. Have a look through the statistics toolbox in the help browser and explore the functions available. .7 Exercises 1.6 The JPL Toolbox The JPL toolbox.spatial-econometics. 15. It is available on the course website. available from http:\\www.com. Best of all. Try downloading this toolbox before writing a custom function to avoid needless replication.

Chapter 16 Optimization The optimization toolbox contains a number of routines to the ﬁnd extremum of a user-supplied objective function. if f is a function to be maximized. obj= x^2-3*x+3+y*x-3*y+y^2. This form is useful when optimization targets require at least two inputs: parameters and data. However. Most of these implement a form of the Newton-Raphson algorithm which uses the gradient to ﬁnd the minimum of a function.hyperparams) x=params(1). obj= x^2+c1*x+c2+y*x+c3*y+y^2. A custom function that returns the function value at a set of parameters – for example a log-likelihood or a GMM quadratic form – is required use one of the optimizers must be constructed. For example consider ﬁnding the minimum of x 2 . Once an optimization target has been speciﬁed. y=params(2). . y=params(2). c1=hyperparams(1). A function which allows the optimizer to work correctly has the form function x2 = optim_target1(x) x2=x^2. Optimization targets can have additional inputs that are not parameters of interest such as data or hyperparameters. − f is a function with the minimum at located the same point as the maximum of f . c3=hyperparams(3). function obj = optim_target3(params. c2=hyperparams(2). All optimization targets must have the parameters as the ﬁrst argument. the next step is to use one of the optimizers ﬁnd the minimum. the objective function must take the form function obj = optim_target2(params) x=params(1). Note: The optimization routines can only ﬁnd minima. When multiple parameters (a parameter vector) are used.

The generic form of fminunc is [p.options. For example. c2=hyperparams(2). . >> hyper = [-3 3 -3]. obj= x^2+c1*x+c2+y*x+c3*y+y^2. indicating the optimization was successful.fval.fval.1 fminunc fminunc performs gradient-based unconstrained minimization. Typically.m.options.’iter’).5).hyper) First-order Iteration 0 1 p = 1 fval = 0 exitflag = 1 fminunc has minimized this function and returns the optimum value of 0 at x = (1. c3=hyperparams(3). c1=hyperparams(1). has the value 1.’Display’. was our objective function and was saved as optim_target4.. three outputs are requested.exitflag]=fminunc(’optim_target4’. Derivatives can be provided by the user or numerically approximated. options is a user supplied optimization options structure (see 16.hyper) which produces >> [p.49e-008 Optimization terminated: relative infinity-norm of gradient less than options. the function value at the optimum (fval) and a ﬂag to determine whether the optimization was successful (exitflag).fval. >> options = optimset(options. .) where fun is the optimization target. .hyperparams) x=params(1). p 0 is the vector of starting values. Values less than or equal to 0 indicate the optimization to not converge successfully.98 Optimization 16. y=params(2). var2 .exitflag]=fminunc(’fun’.TolFun.exitflag]=fminunc(’optim_target4’. var 2 . are optional variables containing data or other constant values.p0. . >> p0 = [0 0]. . and var1 .333333 Step-size optimality 3 1. 1) and the exitflag 1 Func-count 3 6 f(x) 3 0 0. suppose function obj = optim_target4(params.p0 . call >> options = optimset(’fminunc’). the parameters at the optimum (p). var 1 .options.p0. >> [p. To minimize the function. .

However.3 fminbnd fminbnd performs minimization of single parameter problems over a bounded interval using a golden sec- tion algorithm.2 fminsearch 99 16.82712e-010 contract inside contract outside contract inside contract inside Func-count 1 3 5 6 8 min f(x) 3 2. var2 . options is a user supplied optimization options structure (see 16. .exitflag]=fminbnd(’fun’. >> [x.16. are (optional) variables of data or other constant values. . var 1 . fminsearch uses a virtual amoeba to crawl around in the parameter space that will always move to lower objective function values.lb..000000e-004 and F(X) satisfies the convergence criteria using OPTIONS.fval.var 2 .2 fminsearch fminsearch also performs unconstrained optimization but uses a derivative free method (using a simplex). and var1 .8271e-010 exitflag = 1 fminsearch requires more iterations and many more function evaluations and should not be used if fminunc 1.99775 2. . .99475 initial simplex expand reflect expand Procedure Optimization terminated: the current x satisfies the termination criteria using OPTIONS. 16.p0 .. p 0 is the vector of starting values... . var2 . >> options = optimset(’fminsearch’).options.options.0000 fval = 5. . lb and ub are the lower and upper bounds of the parameter. .fval.TolFun of 1. options is a user supplied optimization options structure (see 16.99798e-009 5.hyper) Iteration 0 1 2 3 4 .ub.71526e-009 1. for certain problems.[0 0].99925 2.99775 2.000000e-004 x = 1. . fminsearch may be the only option. 57 58 59 60 107 109 111 113 8. and var1 . fminsearch has the same generic form as fminunc [p.options.5).var 2 .exitflag]=fminsearch(’optim_target4’. var 1 .) where fun is the optimization target. are (optional) variables containing data or other constant values..exitflag]=fminsearch(’fun’.. ..5)..) where fun is the optimization target. >> options = optimset(options. Returning to the previous example but using fminsearch. The generic form is [p. .fval. such as objective functions which are not continuously differentiable.TolX of 1.93657e-009 3. . . .’iter’).’Display’.0000 works satisfactorily.

’Display’.100 Optimization Since fminbnd only minimizes univariate objectives.96601 -3. A is a Q × K matrix and b is a Q × 1 vector.36068 5.exitflag]=fminbnd(’optim_target5’. C N EQ (x ) is a function from K to N and d N EQ if . C (·) is a function from K to M where M is the number of nonlinear inequality constraints. fmincon minimizes f (x ) subject to any combination of • A EQ x = b EQ • Ax ≤ b • C N EQ (x ) = d N EQ • C (x ) ≤ d where x is K by 1 parameter vector. d is a M × 1 vector.fval.’iter’).99997 5. In the second set of constraints.options.1796 2.27864 5 4. consider ﬁnding the minimum of function obj = optim_target5(params. and optimizing using fminbnd >> options = optimset(’fminbnd’). >> hyper=[1 -10 21].hyper) Func-count 1 2 3 4 5 6 x -2. c3=hyperparams(3).hyperparams) x=params(1). >> [x.92236 -4 -4 -4 Procedure initial golden golden parabolic parabolic parabolic Optimization terminated: the current x satisfies the termination criteria using OPTIONS.36068 2.00003 f(x) 50. obj= c1*x^2+c2*x+c3. c2=hyperparams(2). >> options = optimset(options. A EQ is a P × K matrix of b EQ is a P by 1 vector.10.-10.4 fmincon fmincon performs constrained optimizations using linear and/or nonlinear constraints which can be either equality of inequality constraints. c1=hyperparams(1).TolX of 1.000000e-004 x = 5 fval = -4 exitflag = 1 16.

4 -0.b.exitflag]=fmincon(’fun’. . .106 0.4 fmincon 101 an N × 1 vector where N is the number of nonlinear equality constraints.lambda) x1=x(1).fval. p 0 is the vector of starting values.x0. var2 .var 2 .5). UB. The generic form of fmincon is EQ [p. Note: Any ≥ constrain can be transformed into a ≤ constraint by multiplying by −1.LB. x 2 ) = x 1 x 2 −λ subject to a budget constraint p 1 x 1 + p 2 x 2 ≤ 1.529134 constraint -0.. 0 -1. AEQ .options. This is a nonlinear function subject to a linear constraint (note that is must also be that case that x 1 ≥ 0 and x 2 ≥ 0). >> prices >> lambda A = -1 0 1 b = 0 0 1 >> p0=[. >> options = optimset(options. usually off the constraint >> [x. LB and UB are vectors with the same size as p 0 that contain upper and lower bounds. x2=x(2).[].[].b.lambda) max Iter F-count 0 1 3 6 f(x) -0. respectively. suppose the constraint was −1 ≤ p ≤ 1.[].4].’Display’. respectively and b and b EQ are conformable vectors. options is a user supplied optimization options structure (see 16. u=-u %Must change max problem to min!!! The optimization problem can be formulated as >> options = optimset(’fmincon’).nlcon. . nlcon is a nonlinear constraint function that returns the value of C (x ) − d and C N EQ (x ) − d N EQ (This is tricky function. u=x1^(lambda)*x2^(1-lambda). A and A EQ are matrices for inequality and equality constraints.var 1 . λ 1 Consider the problem of optimizing a CRS Cobb-Douglas utility function of the form U (x 1 . . %Change this parameter as needed >> A = [-1 0. then A and b would be A= −1 1 b = 1 1 which are expressions for −p ≤ 1 (which is equivalent to p ≥ −1) and p ≤ 1.[].fval. .’iter’).129 Step-size Directional derivative First-order optimality Procedure 0 -1 1 = [1 1]. 0. %Change this set of parameters as needed = 1/3. %Must start from a feasible position.A. Note: LB and UB can always be represented in A and b .16. . p0 .exitflag]=fmincon(’crs_cobb_douglas’.4.A.) where fun is the optimization target. and var1 . See doc fmincon for speciﬁcs). specify the optimization target function u = crs_cobb_douglas(x. For instance. prices(1) prices(2)] >> b=[0.[]. 1] .b .2 0 1 -0. are (optional) variables containing data or other constant values.options. First.

01e-009 Optimization terminated: first-order optimality measure less than options.529134 0 1 -4.’Display’. In this alternative formulation. >> prices >> lambda = [1 1].3333 0. is used instead. The solution to this problem can be found using >> options = optimset(’fmincon’). Active inequalities (to within options. %This turns it into a <= constraint Ceq = []. function [C. Ceq] = compensated_utility(x. it is necessary to specify a nlcon function.lambda.prices.prices. the optimization problems becomes ¯ min p 1 x 1 + p 2 x 2 subject to U (x 1 .Ubar) x1=x(1).14e-025 2.x 2 Begin by specify an objective function function cost = budget_line(x. even if they do not need them. p1=prices(1). Suppose that dual to the original problem.102 Optimization 2 9 -0.5291 exitflag = 1 upper ineqlin 3 ineqnonlin the exitflag value of 1 indicates success. x2=x(2).Ubar) x1=x(1). that of cost minimization. %No equality constraints Note: The constraint function and the optimization must take the same optional arguments in the same order.TolFun and maximum constraint violation is less than options.TolCon = 1e-006): lower x = 0. %Change this parameter as needed . Since this problem has a nonlinear constraint.6667 fval = -0. x2=x(2).’iter’). cost = p1*x1+p2*x2. u=x1^(lambda)*x2^(1-lambda). >> options = optimset(options. %Note this is a >= constraint C=-con. x 2 ) ≥ U x 1 .lambda. p2=prices(2).TolCon. %Change this set of parameters as needed = 1/3. con=u-Ubar.

.TolFun and maximum constraint violation is less than options.TolCon.02503 0.000283 3.0004091 0.5 1 1 1 1 -1. most are problem class speciﬁc so general rules are hard to derive.b.fval.x0.9709 6.’compensated_utility’.5+1<0 (-u+ubar).451e-005 0.5291.000184 0. Worse.TolCon = 1e-006): lower x = 0.5].05e-007 0. many of the starting values should produce similar parameter estimates and fvals. %Start with all constraints satisfied.982 0.999936 constraint -0. >> [x.952732 0. Practice is the only way to become proﬁcient at function minimization.535e-011 1 0.0001502 1.prices. >> x0 = [1.999936 0. options.9999 exitflag = 1 upper ineqlin ineqnonlin 1 These two examples are problems where the answers can be analytically veriﬁed.0467 0.16.A..31e-008 Line search steplength Directional derivative First-order optimality 0 -1 >> b=[0.6666 fval = 0.05238 0. Note: Many aspects of constrained optimization (and optimization in general) are more black magic than science.[]. 0 -1] %Note. If the optimizer is working well on the speciﬁed problem. Active inequalities (to within options.95 -0.999653 0. The standard practice for addressing the possibility of local minima is to start the optimization from different starting values and then to use the lowest fval.1.5.. require x1>=0 and x2>=0 A = -1 0 b = 0 0 >> Ubar = .Ubar) Max Iter F-count 0 1 2 3 4 5 6 3 6 10 13 16 19 22 f(x) 3 1.[]..615e-007 2.4 fmincon 103 >> A = [-1 0.exitflag]=fmincon(’budget_line’.34e-005 1.lambda. since -1.199 0.[].[]. In many cases it is impossible to verify that the global optimum has been found if there are local minima.999469 0. 0] Optimization terminated: first-order optimality measure less than options.00127 2.0365 0.3333 0.083 0.

individual options can be changed by calling options = optimset(options. semi-inﬁnite constraints fgoalattain Multidimensional goal attainment optimization fminimax Multidimensional minimax optimization lsqlin Linear least squares with linear constraints lsqnonneg Linear least squares with nonnegativity constraints lsqcurvefit Nonlinear curve ﬁtting via least squares (with bounds) lsqnonlin Nonlinear least squares with upper and lower bounds bintprog Binary integer (linear) programming linprog Linear programming quadprog Quadratic programming .6 Other Optimization Routines The Optimization toolbox contains a number of other optimization algorithms: fseminf Multidimensional constrained minimization. >> options = optimset(options.’option2 ’..option value1 .’TolFun’.) For example.1000).’MaxFunEvals’.option value2 . For help on the available options or their speciﬁc meaning.1000. .’MaxIter’. to set options for fmincon.5 optimset optimset sets optimization options and has two distinct forms. . see doc optimset. >> options = optimset(options.1e-3). The initial call to optimset should always be of the form options = optimset(’fmintype’) which will return the default options for the selected optimizer. 16. Once the options structure has been initialized. >> options = optimset(’fmincon’).104 Optimization 16.’option1 ’.

yy Two digit year. or if the dates are delimited using nonstandard characters. For example. or . should be 24 hour format and padded with 0 if single digit MM Minutes. 0000. the format strings above can be used to handle non-standard cases. A few examples >> datenum(’01JAN2000’) ans = . Values stored in this format are as MATLAB serial dates. 17. must be padded with extra 0 if single digit Common string formats are automatically recognized. To call the function with string dates.format ) where format is composed of blocks from yyyy Four digit year. so 12:00 January 1. 2000 is 730. 2000. use either datenum(stringdate) or datenum(stringdate. January) mmm First three letters of month (e.g. The standard method to input dates is to import Excel dates and to add a constant to transform Excel dates – based on January 1.1 datenum datenum converts either string dates (’01JAN2000’) or numeric dates ([2000 01 01]) into MATLAB serial dates. 2000 is 730.g.g. mmmm Full name of month (e.486. However. (e. 20000101). such as yyyyddmm (e. such as a . Dates are natively stored as days since January 0.01). January 1. risky since it can assume the wrong century.g.486. They are particularly useful if the arguments appear in a strange order.5. MATLAB serial dates store hours as fractional days.01. 1900 – to MATLAB serial dates. must be padded with extra 0 if single digit SS Seconds.Chapter 17 Dates and Times Tracking dates is crucial when working with time-series data. JAN) mm Numeric month of year m Capitalized ﬁrst letter of month dddd Full name of weekday ddd First three letters of weekday dd Numeric day of month d Capitalized ﬁrst letter of weekday HH Hour. 0000 is 1 in MATLAB date format and January 1.

17.2000’. >> [years months days] ans = 2000 2000 2000 ans = 730486 730487 730488 datenum can also be used to translate hours.months. For example >> strdates=strvcat(’01JAN2000’. It produces a human readable string from a MATLAB serial date. although it should be 1 1 1 1 2 3 >> datenum(years.01.yyyy’) ans = 730486 >> datenum(’01012000’. it will return string dates of the form ’dd-mmm-yyyy’. such as [2000 01 01] to MATLAB serial date format.106 Dates and Times 730486 >> datenum(’01JAN2000’.’02JAN2000’. However. >> months=[01.JAN.mmm.01].’03JAN2000’) strdates = 01JAN2000 02JAN2000 03JAN2000 >> datenum(strdates) ans = 730486 730487 730488 datenum can also be used to convert numeric dates. By default.02. >> datenum([2000 01 01]) ans = 730486 >> years=[2000. it also knows a number of stan- .2000]. For example.2000.’dd.’ddmmyyyy’) ans = 730486 datenum also works on string arrays.’ddmmmyyyy’) ans = 730486 >> datenum(’01. >> days=[01.days) easy to write code to handle this. minutes and seconds to fractional days.03].2 datestr datestr is the “inverse” of datenum.

use datestr(serial_date.’03JAN2000’)) serial_date = 730486 730487 730488 >> datestr(serial_date) ans = 01-Jan-2000 02-Jan-2000 03-Jan-2000 17. >> serial_date=datenum(strvcat(’01JAN2000’.’02JAN2000’.g. yyyy’ to produce a date string with .01. For example. datestr can also produce strings with arbitrary formats using the syntax detailed above (e. delimiters).0) ans = 01-Jan-2000 00:00:00 >> datestr(serial_date. #) where # corresponds to one of the format strings (see doc datestr for a list). ’dd.’02JAN2000’. mm.dd.dd. >> serial_date=datenum(’01JAN2000’) serial_date = 730486 >> datestr(serial_date) ans = 01-Jan-2000 >> datestr(serial_date. datestr can take a vector input and return a vector output. datevec will produce a K × 6 vector of the form [Year Month Day Hour Minute Second].3 datevec ×1 datevec converts MATLAB serial dates into human parsable numeric formats.2000 Like datenum.’mmm.5 >> datevec(serial_date) ans = 2000 2000 2000 1 1 1 1 2 3 0 0 12 0 0 0 0 0 0 corresponds to 0:00 (midnight) on the January 1-2.’03JAN2000 12:00:00’)) serial_date = 730486 730487 730488.yyyy’. 2000 and 12:00 (noon) on January 3. 2000. given a K vector containing MATLAB serial dates.yyyy’) ans = Jan. >> serial_date=datenum(strvcat(’01JAN2000’. . To produce one of the nonstandard date formats.17.3 datevec 107 dard formats such as ’mm/dd/yy’ or ’mmm. Speciﬁcally.

2.. >> axis tight >> serial_dates=datenum(strvcat(’01/01/2000’. for i=1:10000000. >> h=plot(dates.’keeplimits’) as illustrated in ﬁgure 17.’01/03/2000’. >> j=1. end >> toc Elapsed time is 0. for i=1:1000000.1). >> e=etime(clock. >> subplot(2. 17.. >> datetick(’x’) produces the two plots in ﬁgure 17. For example. >> plot(dates.5 tic and toc tic and toc can be used for timing code to ﬁnd hot spot – segments of code which take the majority of the computational time. The top plot contains MATLAB serial dates along the x-axis while the bottom contains sting dates. datetick converts an axis of a plot expressed in MATLAB serial dates to text dates. rw). datetick also understands both standard formatting commands (see datestr) and custom formatting commands (see datenum). rw).2. rw).c) e = 0.1. >> rw = cumsum(randn(size(dates))). For example. This function has an unfortunate tendency to produce few x-labels. Clock returns a 1 × 6 vector (same format as datevec) of the computer clock.’01/04/2000’.. >> plot(dates.’keepticks’.1. >> subplot(2. 17.108 Dates and Times 17. >> c=clock..010740 seconds. The solution is to ﬁrst choose the axis label points (in serial dates) and than use datetick(’x’. j=j+1.4 now and clock now returns the a MATLAB serial date representation of the computer clock.4830 17. datevec(now) produces the same output as clock.’01/02/2000’.7 datetick datetick is not a function for explicitly working with dates. >> dates = datenum(’01Jan2000’):datenum(’31Dec2000’). >> tic >> j=1.1). j=j+1.6 etime The elapsed time between two calls to clock can be computed using etime. . end.

>> datetick(’x’.’01/10/2000’. ’01/05/2000’.serial_dates).1: Example of datetick.3075 7.’01/08/2000’.306 7..’keepticks’.3055 7.’01/06/2000’.’keeplimits’).307 7.’Parent’).’dd/mm’.3045 109 7. ’dd/mm/yyyy’).7 datetick 10 5 0 −5 −10 −15 −20 7..’XTick’.’keeplimits’. ’01/09/2000’. datetick converts MATLAB serial dates into text strings.’01/11/2000’. >> set(parent.’01/12/2000’)..309 x 10 5 10 5 0 −5 −10 −15 −20 Q1−00 Q2−00 Q3−00 Q4−00 Q1−01 Figure 17. Unfortunately.’01/07/2000’. The solution is to use datetick(’x’. >> xlabel(’Date’) >> ylabel(’Level’) >> title(’Demo plot of datetick with keeplimits and keepticks’) ....3085 7.308 7. >> parent=get(h.3065 7.17.’keeplimits’).305 7. datetick changes the location of points and makes fairly bad choices.

’keeplimits’).’keepticks’. .110 Dates and Times Demo plot of datetick with keeplimits and keepticks 5 0 Level −5 −10 −15 01/01 01/02 01/03 01/04 01/05 01/06 01/07 Date 01/08 01/09 01/10 01/11 01/12 Figure 17. set up the ﬁgure as is should look but with serial dates. To use them. and then call datetick(’x’. These two arguments ensure datetick behaves sanely.2: datetick with keepticks and keeplimits.

>> double(’MATLAB’) ans = 77 97 116 108 97 98 . str(1:10)). >> char(65:100) ans = ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_‘abcd >> char([1. Chapter 3 contains an example of parsing a poorly formatted ﬁle. Since character data are contained in matrices. The primary application of string functions is to parse data. they respect the standard behavior of most commands (e. char char changes integer numerical values between 1 and 255 into their ASCII equivalent characters. the programming environment does provide a complete set of tools for working with strings.’. Simple strings can be input from the command line str = ’Econometrics is my favorite subject.32 pi 256]) ans = double double changes character strings into their numerical values. However.Chapter 18 String Manipulation While manipulating text is not MATLAB’s forté. using commands designed for numerical data is tedious and special purpose functions are provided to assist with string data. It uses a number of string functions to manipulate and parse the text of a ﬁle.g. Strings are treated as matrices of character data. Other values produce a nonsense result.

If more than one character is searched for. >> str = ’ababababa’ str = . It is useful in ﬁnding delimiting char- acters in a block of text. >> y=strvcat(’delta’.9:30:07.’d’)) ans = ac bd >> strcat(strvcat(’a’. two matrices x and y can be vertically concatenated by [x. strvcat makes this easy. >> strvcat(x.5’. consider a single line from WRDS TAQ output >> str = ’IBM.y) ans = alpha beta delta gamma strcat strcat horizontally concatenates strings. If one has a single row.y]. z=strcat(x.’banana’. For example. strcat concatenates it to every row of the other vector.’beta’).84.’gamma’). >> strcat(strvcat(’a’.’) ans = 4 14 22 strfind returns all of the location of ’.’. >> strvcat(’apple’.112 String Manipulation strvcat strvcat vertically concatenates two strings.’cherry’) ans = apple banana cherry >> x=strvcat(’alpha’.’c’) ans = ac bc strfind strfind returns the index of the all matching strings in a text block.’.’b’).02JAN2001. In normal math mode. strfind can produce overlapping blocks.’b’).strvcat(’c’. However.y) is the same as z=[x y] when x and y have the same number of rows. strings often have different widths which makes vertical concatenation difﬁcult. >> strfind(str.

use the optional command ’exact’ >> str = strvcat(’alpha’.’apple1’. To match only the entire row.’alphabeta’). >> strmatch(’alpha’. strcmpi does the same but is not case sensitive.’A’) ans = 1 strncmp and strncmpi strncmp compares the ﬁrst n characters of two strings and returns (logical) 1 if they are the same.’Apple1’.’a’) ans = 1 >> strcmp(’a’. It is case sensitive.5) ans = 0 >> strncmpi(’apple’.5) ans = 1 >> strncmp(’apple’.’A’) ans = 0 >> strcmpi(’a’.’beta’. >> strncmp(’apple’.6) ans = 0 >> strncmp(’apple’.str) ans = 1 .113 ababababa >> strfind(str.’Apple1’.’apple1’.5) ans = 1 strmatch strmatch compares rows of a character matrix with a string and returns the index of all rows that begin with the string. >> strcmp(’a’. strcnmpi does the same but is not case sensitive.’aba’) ans = 1 3 5 7 strcmp and strcmpi strcmp compares two strings and returns (logical) 1 if they are the same. It is case sensitive.

The input can be scalar. Unlike str2num it only operates on scalars or cell arrays. vector or matrix valued.’2’. For examples of regexp. >> strvcat(’1’. see doc regexp.’2’.4 5 6]) ans = .’exact’) ans = 1 regexp and regexpi regexp is similar to strfind but takes standard regular expression syntax commands.’4 5 6’]) ans = 1 4 2 5 3 6 Note the different spacing of strings and numbers. num2str num2str converts numerical values into strings.str. The input can be either vector or matrix valued. It is case sensitive.’3’) ans = 1 2 3 >> str2num(strvcat(’1’.114 String Manipulation 3 >> strmatch(’alpha’.2. str2double str2double converts string values into numerical varies.3]) ans = 1 2 3 >> num2str([1 2 3. str2num str2num converts string values into numerical varies. regexpi does the same but is not case sensitive. str2double offers better performance when it is applicable. >> num2str([1.’3’)) ans = 1 2 3 >> str2num([’1 2 3’.

shares out standing. delimited and contain stock name. and price. date should be a MATLAB serial data. Load the ﬁle hardtoparsetext. . date of observation. and shares outstanding and price should be numerical. Write a program that will loop over the rows and parse the data into four variables: ticker. For help converting the dates to serial dates.mat and inspect the variable string_data. use NaN.18. shares and price. Note: Ticker should be a string. The data in this ﬁle are . For values of ’N/A’. see chapter 17.1 Exercises 1.1 Exercises 115 1 4 2 5 3 6 18.date.

116 String Manipulation .

Structures are constructed using variable_name.Chapter 19 Structures and Cell Arrays Structures and cell arrays are advanced data storage formats that often provide useful scaffolding for working with structured data.y = -1 coord = x: 0. Consider the case of working with data that comes in triples which correspond to x-. 19. Alternatively.1 Structures Structures allow related pieces of data to be organized.y = 2 . Structure arrays can be constructed using the command struct. >> coord(2). y and z to provide added guidance on what is expected.ﬁeld_name syntax where both variable_name and ﬁeld_name should be satisfy the constraints on variable names.5 coord = x: 0.x = 3 coord = 1x2 struct array with fields: x y z >> coord(2).5000 y: -1 >> coord.5000 >> coord. or can be lazily initialized by concatenation. y. One alternative would be to store the data as a 3 by 1 vector.x = 0. Continuing from the previous example.and z-data. a structure could be used with ﬁeld names x. Structures can be used to organize data.5000 y: -1 z: 2 Structures can also be used in arrays (array of structures).z = 2 coord = x: 0. >> coord.

4019e+012 >> contact. Structures are also difﬁcult to preallocate and so will produce performance issues if used in large arrays.118 Structures and Cell Arrays coord = 1x2 struct array with fields: x y z >> coord(2). . >> contact.name = ’Kevin Sheppard’ contact = phoneNumber: 4.2 Cell Arrays Cell arrays are a powerful alternative to the “everything is a matrix” model of classic MATLAB. 19. in optimset). In either case.phoneNumber = 4401865281165 contact = phoneNumber: 4. >> newCoord = coord(1) newCoord = x: 0.z = -1 coord = 1x2 struct array with fields: x y z The elements of the array of structures can be accessed like any other array with the caveat that the assignment will itself be a structure. The are most useful when handling either pure string data or mixed data which contains both string values and numbers. although they have been supplanted by a more useful object.5000 y: -1 z: 2 Structures can also be used to store mixed data. Cell arrays are formally jagged (or ragged) arrays and are collections of other arrays. The example below shows how cell arrays can be pre-allocated using cell and then populated using braces. and that operating on structures requires operating on the ﬁelds one-at-a-time.4019e+012 name: ’Kevin Sheppard’ 19.1. Cell arrays can be initialized using the cell command or directly using braces ({}). braces are used to access elements within a cell array. Cell arrays can be through of as generic containers where each element is a matrix. Cell arrays is similar to other commands in MATLAB although there are some important caveats.1 The Problem with Structures The fundamental problem with structures in MATLAB is that they are difﬁcult to work with. Structures are still collonly used (for example. the cell array.

and so can be used to store virtually any data structure by nesting. only the second was empty. Cell arrays can even contain other cell arrays.1) cellArray = ’string’ [1x5 double] {2x1 cell } .2 Cell Arrays 119 % Initialize a cell array >> cellArray = cell(2. Finally. >> cellArray{1} = ’string’ cellArray = ’string’ [] >> cellArray{2} = [1 2 3 4 5] cellArray = ’string’ [1x5 double] >> cellArray{2} ans = 1 2 3 4 5 The cell array above has a string in the ﬁrst position and a 5 by 1 numeric vector in the second. % Initialize a cell array >> cellArray = cell(2. the string vector ’array’ was placed into the second position. as the next example shows. After the string vector ’cell’ was added in the ﬁrst position. Cell arrays are also adept at handling mixed data.19.1). This simple example show the ease with which cell arrays can be used to handle strings as opposed to using matrices of characters which becomes problematic when some of the row may not have the same number of characters and so need to be padded with blank characters (and then often deblanked before actually being used in code).1) cellArray = [] [] % Add an element using braces { } >> cellArray{1} = ’cell’ cellArray = ’cell’ [] >> cellArray{2} = ’array’ cellArray = ’cell’ ’array’ Initially the variable was an empty cell array. % Initialize a cell array >> cellArray{3} = cell(2.

120

Structures and Cell Arrays

19.3

Accessing Elements of Cell Arrays

The primary method for accessing cell arrays is through the use of braces ({}) as the two previous examples demonstrated. Selecting an element using braces returns the contents of the cell and can be used to assign the values for processing using functions that are not designed for cell arrays. Continuing from the previous example,

>> x = cellArray{1} x = string >> y = cellArray{2} y = 1 2 3 4 5

Cell arrays can also be accessed using parentheses although this type of access is markedly different from accessing cell arrays with braces. Unlike braces which access the contents of a cell, parentheses access the cell itself and not its contents. The difference in behavior means that subsets of a cell array can be assigned to another variable without iterating across the contents of the cell array.

>> cellArray = cell(3,1); >> cellArray{1} = ’one’; >> cellArray{2} = ’two’; >> cellArray{3} = ’three’; cellArray = ’one’ ’two’ ’three’ % Correct method to reassign elements of a cell array to a new array using parentheses ( ) >> newCellArray = cellArray(1:2) newCellArray = ’one’ ’two’ % Incorrect method to reassign elements of a cell array to a new array using braces { } >> newCellArray = cellArray{1:2} newCellArray = one

In the example above, newCellArray contains the ﬁrst elements of cellArray. Also note the incorrect attempt to assign the ﬁrst two elements using braces which does not produce the desired result.

19.4

Considerations when Using Cell Arrays

Cell arrays, like structures, are useful data structures for working with strings or mixed data. Cell arrays are generally superior to structures and there are many functions which can operate directly on cell arrays of strings (e.g. sort, unique, ismember). They do come with some overhead and so are not appropriate for every use. For example, a 2 by 1 vector containing [1 2]’ requires 16 bytes of memory. A cell array with 1 in its ﬁrst cell and 2 in its second requires 240 bytes of memory, a 15 fold increase. Due to this overhead cell

19.4 Considerations when Using Cell Arrays

121

arrays are undesirable in situations where data is highly regular and where the contents of each cell is small.

122

Structures and Cell Arrays

name) . . >> d = dir(’*.’Nothing to see’). next to the Current Directory box at the top of the command window (see ﬁgure 1. to change directory.demotxt’].1). 20. fprintf(fid. such as dir and mkdir are also available. % Create some files for i=1:3.Chapter 20 File System and Navigation MATLAB uses standard DOS ﬁle system commands to change working directories. type cd c:\MyDirectory Other standard DOS ﬁle navigation commands. ﬁurst displaying the ﬁle name and then using type to print the contents of the ﬁle. which can be done by looping over the output of dir. One common application of programatic access to the ﬁle system is to perform some action on every ﬁle in a particular directory.’wt’). the current directory can be changed by clicking the button with . fclose(fid). . Alternatively.demotxt’) d = 3x1 struct array with fields: name date bytes isdir datenum >> for i=1:length(d). This method is very useful for processing large numbers of data ﬁles. >> disp(d(i). For instance. fid = fopen([’file_’ num2str(i) ’. end The example code below get a list of ﬁles that have the extension demotxt and then loops across the ﬁles.1 Addressing the File System Programmatically The ﬁle system can be used in MATLAB code.

demotxt Nothing to see file_2. chapter20 (mkdir). the MATLAB program directory will be read only and the original MATLAB path cannot be directly altered. The path is sorted from the most important directory to least. create and save a ﬁle named startup. enter path in the command window. New directories can be appended to the path using addpath or File>Set Path. This is useful for detecting duplicate ﬁle names. but it may be necessary to add new directories to use custom or a non-standard toolbox. use the command savepath or click on Save Path in the Path GUI. The path determines which ﬁles MATLAB will use when evaluating a function or running a batch ﬁle.124 File System and Navigation >> type(d(i). Alternatively. . . To save any changes. Suppose a custom function is accidentally titled mean. The path determines where MATLAB searches for ﬁles when running m-ﬁles. with the present working directory (what pwd returns in the command window) silently atop the list. . . Because of this. returning them in the order they appear on the path. where ’Path to Add’ and ’Second Path to Add’ are directories to be added to the base path. To work around this issue. it is crucial that existing function names are avoided when writing m-ﬁles.3 Using a Custom Path in a Shared Environment In most shared environments. . The highest ranked ﬁled will then be executed.demotxt Nothing to see file_3. All of the toolbox directories are automatically on the path. To see the current path. 20.m in U:\MATLAB. MATLAB will automatically look in the startup directory for this ﬁle and execute it when launched. MATLAB will ﬁnd all occurrences of mean on the path and rank them based on the order the ﬁles appear.name) >> end file_1.2 The MATLAB Path While this section sounds like a Buddhist rite of passage. . The GUI tool can be used to re-rank directories on the path. the path is an important set of locations. Use the command window to create a new directory.demotxt Nothing to see 20.4 Exercises 1. This ﬁle should contain the following: addpath(’U:\Path to Add’). which function -all will show all ﬁles that match function (function. m-ﬁles and mat ﬁles). there is a GUI path browser available under File>Set Path.. When mean is entered in the command window. 20. addpath(’U:\Second Path to Add’).

Delete the newly created m-ﬁle. Get the directory listing using dir. Change into this directory using cd. 4.4 Exercises 125 2. 3. Add this directory to the path using either addpath or the Path GUI. Create a new ﬁle names tobedeleted. Remove this folder from the path using either rmpath or the Path GUI. 7. Save the changes using either savepath or the Path GUI. and then delete this directory from the command line. 5. 6.20. .m using the editor in this new directory (It can be empty).

126 File System and Navigation .

end. possibly slow. algorithm implementation as an initial versions on a problem.Chapter 21 Performance and Code Optimization The ﬁnal step in writing code is to optimize the performance of the code. Preallocating data arrays allows expensive memory allocation to be avoided in the core of the program and pregenerating random numbers allows function overhead to be avoided. consider the following code: y = 0.1). 21. tic. In some cases the improvements can be 100 times or greater and the largest gains come from removing superﬂuous memory allocations. y(i) = y(i-1) + randn.001615 seconds. . A good practice is to use a simple. end. Code optimization can produce large improvements in speed over a naïve (but correct) implementation. Warning: Be careful not to over-optimize code.145061 seconds. for i=2:10000. toc Elapsed time is 0.1 Pre-allocate Data Arrays Pre-allocating data and pre-generating random numbers in large blocks is the most basic optimization. To see the effects of pre-allocating. Over-optimizing code can produce code that is unreadable and difﬁcult to debug. The optimized version can be built from the known-good code and the output from the optimized code can be compared to the known-correct output. if needed. y = zeros(10000. toc Elapsed time is 0. for i=2:10000. y(i) = y(i-1) + randn. tic.

1 + . y = zeros(100000. The gain in this case is 30%. end.5 -. end. This abstraction comes at the cost of performance and memory allocation is slow.011111 seconds.2y t −2 + 0. for i=1:2 y(t) = y(t) + parameters(i+1)*y(t-i). tic for t=3:10000 y(t) = parameters(1).1). e=randn(100000.023440 seconds. y = zeros(10000.1 .014133 seconds. y(i) = y(i-1) + e(i).1). 21. tic. end for i=0:1 y(t) = y(t) + parameters(5-i)*epsilon(t-i).128 Performance and Code Optimization The second version with a pre-allocated y is 80 times faster.5y t −1 − . y(i) = y(i-1) + randn. parameters = [. end toc Elapsed time is 0. consider the two implementations of the following recursion y t = .2 . end end .for i=2:100000. tic.1). consider the following code: y = zeros(100000. toc Elapsed time is 0. toc Elapsed time is 0. tic for t=3:10000 y(t) = parameters * [1 y(t-1) y(t-1) epsilon(t-1) epsilon(t)]’.1). for i=2:100000.1).2 Avoid Operations that Require Allocating New Memory One of the key advantages to using an environment such as MATLAB is that end-users are not required to manage memory.8 1].8εt −1 + εt epsilon = randn(10000. For an example of the penalty. To see the effects of pre-generating random numbers.

For example if the optimization target is a likelihood target that depends on the square of the data (e.5 Use M-Lint The editor provides M-Lint guidance when available.21. The second implementation uses more loops but avoids costly memory allocation. 21. The second implementation is 11 times faster because it avoids allocating memory inside the loop.3 Use Vector and Matrix Operations 129 toc Elapsed time is 0. tic op_fast = X’*X. X = randn(N. toc Elapsed time is 0. op = zeros(10). [1 y(t-1) y(t-1) epsilon(t-1) epsilon(t)] requires a new. tic for n=1:N op = op + X(n.:). In the ﬁrst implementation.3 Use Vector and Matrix Operations Vector and matrix operations are highly optimized and writing code in matrix-vector notation is faster than looping. pre-computing the square of the data and passing it as one of the optional arguments avoids needlessly re-computing these values every time the objective function is called. the Gaussian loglikelihood). N = 10000. end toc Elapsed time is 0.4 Use Pre-computed Values in Optimization Targets Many optimization targets will depend on parameters. empty 5 element vector to be allocated in memory and then for the 5 elements to be copied into this vector every iteration. In many cases the functions of the data do not depend on the parameter values allowing them to be pre-computed. Consider the problem of computing N XX= n=1 xn xn which is the inner product of a matrix.g. data and functions of data. 21. 21. .000940 seconds.056590 seconds. This advice is almost always correct and should only be ignored if known to be wrong.:)’*X(n.001933 seconds.10).

130 Performance and Code Optimization 21. This allows hot-spots in code – code segments which require the most time – to be identiﬁed so that optimization can be focused on the code that spends the most time running. .6 Proﬁle Code to Find Hot-Spots The ﬁnal and most advanced optimization tool is the proﬁler. The second run the code to be proﬁled. The ﬁnal command turns the proﬁler off and opens the proﬁle report viewer. Running through the proﬁler records every line executed and the time required to execute. The proﬁler is run using >> profile on >> code_to_profile >> profile viewer The ﬁrst command turns the proﬁle on.

The state for randn is a 2 by 1 vector.state) >> state = randn(’state’). . The state for rand is either a 35 by 1 vector (old version) or a 625 by 1 vector (new version.1) • randn: Standard Normal pseudo-random number generator The distribution of pseudo-random number generated will determine which of these are used.state) or rand(’twister’. known as twister). For example. This allows Monte Carlo results to be replicated across different version of code or on different computers.1 The state can be restored using randn(’state’. Both Students-t and χ 2 pseudo-random numbers call both rand and randn. Weibull pseudo-random numbers use rand. Normal pseudo-random numbers obviously call randn.Chapter 22 Simulation and Random Number Generation 22. 22. state = 3950588338 2796772805 >> randn ans = 0. twister may not be available and the state can be saved using state = rand(’state’).778806031346949 >> randn ans = 0.645328521657827 1 If using an old version of MATLAB.2 Replicating Simulation Data The two core pseudo-random number generators each have a state.1 Core Random Number Generators All pseudo-random numbers are generated by two core random number generators. The state can be retrieved using state = randn(’state’) for the Normal pseudo-random number generator and state = rand(’twister’) for the uniform pseudo-random-number generator. • rand: Uniform pseudo-random number generator on the interval (0. Saving and the restoring the state allows the same sequence of pseudo-random numbers to be generated.

’seed’. Two avoid this problem the state needs to be initialized using a “random” value such as the time the program began running.sum(100*clock))) In older version of MATLAB the random numbers needed to be separately initialized.100*sum(clock)). >> randn(’state’. will be identical. Repeatedly re-initializing the pseudo-random number generators will produce a sequence that is much less random than the generator was designed to provide. >> randn ans = 0.778806031346949 >> randn ans = 0.132 Simulation and Random Number Generation >> randn(’state’.100*sum(clock)).3 Considerations when Running Simulations on Multiple Computers The state of both rand and randn is reset each time MATLAB is opened.645328521657827 These two sequences are the same since the state was restored to its previous value. The same can be accomplished with rand using rand(’twister’) (new version) or rand(’state’) (old version). or in two instance on the same computer. The generators should be initialized once per session and then allowed to produce the sequence beginning with the state set by clock.setDefaultStream(RandStream(’mt19937ar’. >> rand(’twister’. Thus two programs drawing pseudorandom numbers on different computers. 22. .state). Warning: Do not over-initialize the pseudo-random number generators. This can be accomplished in recent versions of MATLAB by RandStream.

Returns complex values for negative elements. diff Returns the difference between two adjacent elements of a vector.Chapter 23 Quick Function Reference This list contains a brief summary of the functions most useful in the MFE course. If used on a complex data. There are approximately 100 functions listed here. MATLAB and the Statistics Toolbox combined contain more than 1400. 23. log Returns the natural logarithm of the elements of a vector or matrix. returns a matrix of differences of each column. exp Returns the exponential function (e x ) of the elements of a vector or matrix. The if the original vector has length T . vector returned has length T − 1. It only scratches the surface of what MATLAB offers. Returns complex values for negative elements. . log10 Returns the logarithm base 10 of the elements of a vector or matrix. returns the complex modulus. The matrix returned has one less row than the original matrix. If used on a matrix.1 abs General Math Returns the absolute value of the elements of a vector or matrix.

sum Returns the sum of the elements of a vector. mean Returns the arithmetic mean of a vector. of the elements of a vector or matrix. returns a row vector containing the maximum of each column. returns a row vector containing the minimum of each column.134 Quick Function Reference max Returns the maximum of a vector. Operates elementby-element on vectors or matrices. . Operates element-by-element on vectors or matrices. Operates element-by-element on vectors or matrices. min Returns the minimum of a vector. 23. sign Returns the sign. sqrt Returns the square root of a number. If used on a matrix. operated column-by-column.2 ceil Rounding Returns the next larger integer. roots Returns the roots of a polynomial. mod Returns the remainder of a division operation where the elements of a vector or matrix are divided by a scalar or conformable vector or matrix. floor Returns the next smaller integer. Operates element-by-element on vectors or matrices. If used on a matrix. deﬁned as x /|x | and 0 if x = 0. returns a row vector containing the mean of each column. If used on a matrix. If used on a matrix.

If a matrix x is N by M . If used on a matrix. produces the same output as var.3 Statistics 135 round Rounds to the nearest integer. . a row vector containing the percentiles of each column is returned. If a matrix x is N by M . a row vector containing the kurtosis of each column is returned. If used on a matrix. prctile Computes the percentiles of a vector. If used on a vector. returns the M by M correlation treating the columns of x as realizations from separate random variables. median Returns the median of a vector. If used on a matrix. regress Estimates a classic linear regression. a row vector containing the median of each column is returned. 23. Does not compute White heteroskedasticity-robust standard errors. Operates element-by-element on vectors or matrices. quantile Computes the quantiles of a vector.3 Statistics corrcoef and corr Computes the correlation of a matrix. returns the M by M covariance treating the columns of x as realizations from separate random variables. skewness Computes the skewness of a vector. cov Computes the covariance of a matrix.23. If used on a matrix. a row vector containing the quantiles of each column is returned. If used on a matrix. a row vector containing the skewness of each column is returned. kurtosis Computes the kurtosis of a vector.

Weibull. One of three core random number generators that are used to produce pseudo-random numbers from other distributions. . Geometric. Generalized Extreme Value. Gamma. randg Standard gamma pseudo-random number generator. Hypergeometric. Binomial. Negative Binomial.4 rand Random Numbers Uniform pseudo-random number generator. 23. One of three core random number generators that are used to produce pseudo-random numbers from other distributions. Rayleigh. D I ST cdf Returns the cumulative distribution function values for a given D I ST . Noncentral t . norm (normcdf). where D I ST takes one of many forms such as t (tcdf). Noncentral F . where D I ST takes one of many forms such as t (tpdf). var Computes the variance of a vector. t . D I ST pdf Returns the probability density function values for a given D I ST . Generalized Pareto. Uniform. where D I ST takes one of many forms such as t (trnd). Uniform. or gam (gamcdf). D I ST rnd Produces pseudo-random numbers for a given D I ST . where D I ST takes one of many forms such as t (tinv). Inputs vary by distribution. Poisson. Discrete. or gam (gamrnd). Note: D I ST function are available for the following distributions: Beta.136 Quick Function Reference std Computes the standard deviation of a vector. If used on a matrix. a row vector containing the standard deviation of each column is returned. χ 2 . D I ST inv Returns the inverse cumulative distribution value for a given D I ST . or gam (gampdf). Lognormal. norm (normrnd). or gam (gaminv). Extreme Value. If used on a matrix. norm (norminv). Inputs vary by distribution. Normal. norm (normpdf). Inputs vary by distribution. Inputs vary by distribution. a row vector containing the variance of each column is returned. F . Exponential. Noncentral χ 2 .

Operates element-by-element on vectors or matrices. isfinite Returns logical true if the argument is ﬁnite. χ 2 . any Returns logical true (1) if any elements of a vector are logical true. Weibull. Extreme Value. Uniform.23. Noncentral t . ischar Returns logical true if the argument is a string. random Generic pseudo-random number generator. Operates element-by-element on vectors or matrices. Poisson. returns a row vector containing logical true if any elements of each column are logical true. Negative Binomial. Geometric. Can generate random numbers for the following distributions: Beta. isinf Returns logical true if the argument is inﬁnite. Noncentral F . Uniform. Lognormal. Exponential. find Returns the indices of the elements of a vector or matrix which satisfy a logical condition. F .5 Logical 137 randn Standard normal pseudo-random number generator. If used on a matrix. Operates element-by-element on vectors or matrices. . Noncentral χ 2 .5 all Logical Returns logical true (1) if all elements of a vector are logical true. 23. isnan Returns logical true if the argument is not a number (NaN). One of three core random number generators that are used to produce pseudo-random numbers from other distributions. Discrete. Gamma. Generalized Extreme Value. isreal Returns logical true if the argument is not complex. Normal. Generalized Pareto. t . If used on a matrix. returns a row vector containing logical true if all elements of each column are logical true. Rayleigh. Binomial. Hypergeometric.

138 Quick Function Reference logical Converts non-logical variables to logical variables. It occurs as a results of performing an operation which produces in indeﬁnite result.U . Inf Inf represents inﬁnity. such as Inf/Inf.6 ans Special Values ans is a special variable that contains the value of the last unassigned operation. pi Returns the value of π.7 eye Special Matrices z=eye(N ) returns a N by N identity matrix. toeplitz z=toeplitz(x) returns a Toeplitz matrix constructed from a vector x.M ) returns a N by M matrix of ones.N ) returns a 1 by N vector of points uniformly spaced between L and U (inclusive). 23. 23. logspace z=logspace(L . Operates element-by-element on vectors or matrices. eps eps is the numerical precision of MATLAB.U . NaN NaN represents not-a-number. Numbers differing by more the eps are numerically identical. . linspace z=linspace(L . ones z=ones(N .N ) returns a 1 by N vector of points logarithmically spaced between 10L and 10U (inclu- sive).

triu Returns a upper triangular version of the input matrix. equivalent to sum(diag(x)).M ) returns a N by M matrix of zeros. eig Returns the eigenvalues and eigenvectors of a square matrix. . inv Returns the inverse of a square matrix. tril Returns a lower triangular version of the input matrix.23. i j =1 x j . kron Kronecker product of two matrices. det Computes the determinant of a square matrix. y = cumprod(x) computes y i = operates column-by-column. returns a matrix with the elements of the vector along the diagonal. trace Returns the trace of a matrix. diag Returns the elements along the diagonal of a square matrix.8 chol Vector and Matrix Functions Computes the Cholesky factor of a positive deﬁnite matrix. If the input to diag is a vector.8 Vector and Matrix Functions 139 zeros z=zeros(N . 23. If used on a matrix. cumprod Computes the cumulative product of a vector.

Can be used with optional ’rows’ argument and same-sized matrices to produce an intersection of the rows of the two matrices. setdiff Returns the difference between the elements of two vectors. i j =1 x j . cat(1. numel Returns the number of elements in a matrix.y) is the same as [x. The product of the dimensions must be the same before and after. Dimension 1 is the number of rows and dimension 2 is the number of columns.x. If the matrix is 2D with dimensions N and M . repmat Replicates a matrix according to the dimensions provided.y) is the same as [x y]. . y = cumsum(x) computes y i = operates column-by-column. 23. length Length of the longest dimension of a matrix and is equivalent to max(size(x)). hence the number of elements cannot change.9 cat Matrix Manipulation Concatenates two matrices along some dimension.10 Set Functions intersect Returns the intersection of two vectors. If used on a matrix.x. size Returns the dimension of a matrix. reshape Reshapes a matrix to have a different size. If x and y are conformable matrices. numel returns NM. 23. y] and cat(2. Can be used with optional ’rows’ argument and same-sized matrices to produce a matrix containing difference of the rows of the two matrices.140 Quick Function Reference cumsum Computes the cumulative sum of a vector.

. 23. elseif Command that is used to continue a if . else ﬂow control block. . . . . . otherwise must be terminated with an end. the else path is followed. . if Command that is used to begin a if . elseif . If none of the if or elseif statement are evaluated to logical true. else ﬂow control blocks. . else ﬂow control block.23. . elseif . otherwise ﬂow control block. . . Can be used with optional ’rows’ argument on a matrix to select the set of unique rows. If used on a matrix. . else and switch . elseif . . . union Returns the union of two vectors.11 Flow Control 141 sort Produces a sorted vector from smallest to largest. . case . else Command that is the default in if . sortrows Sorts the rows of a matrix using lexicographic ordering (similar to alphabetizing words). . . . . Should be immediately followed by a statement that can be evaluated to logical true or false. elseif . end Command indicating the end of a ﬂow control block. Can be used with optional ’rows’ argument and same-sized matrices to produce an union of the rows of the two matrices.11 case Flow Control Command which can be evaluated to logical true or false in a switch . . Also ends loops. . . operates column-by-column. unique Returns the unique elements of a vector. case . Should be immediately followed by a statement that can be evaluated to logical true or false. . Both if . . .

while One of two types of loops. for loops iterate over a predeﬁned vector unless prematurely ended by break. .142 Quick Function Reference switch Command signalling the beginning of a switch . fmincon Constrained function minimization using a gradient based search. .13 fminbnd Optimization Function minimization with bounds. .12 continue Looping Forces a loop to proceed to the next iteration while bypassing any code occurring after the continue statement. Find the minimum of a function that exists between L and U . fminsearch Function minimization using a simplex (derivative-free) search. for One of two types of loops. case . Also ends ﬂow control blocks. . 23. 23. otherwise ﬂow control block. . fminunc Unconstrained function minimization using a gradient based search. While loops continue until some logical condition is evaluated to logical false (0) unless prematurely ended by a break or continue command. Switch should be followed by a variable to be used by case. break Prematurely breaks out of a loop before the all iterations have completed. end All loop blocks must be terminated by an end command. Constraints can be linear or non-linear and equality or inequality.

14 axis Graphics Sets or gets the current axis limits of the active ﬁgure. When used with a number. bar3 Produces a 3-D bar plot of a vector or matrix. that ﬁgure is set as the active ﬁgure and any subsequent plot commands will operate on Figure X X . optimset Sets options structure for optimization. figure Opens a new ﬁgure window. get Gets of list of properties from a graphics handle or the value of a property if used with an optional second argument. errorbar Produces a plot of x data against y data with error bars (conﬁdence sets) around each point.14 Graphics 143 optimget Gets options structure for optimization. 23. Can also be used to tighten limits using the command axis tight. contour Produces a contour plot of the levels of z data against vectors of x and y data. If a windows with label Figure X X is already open. . for example figure(X X ) opens a window with label Figure X X where X X is some integer. bar Produces a bar plot of a vector or matrix. colormap Colors ﬁgures according to the selected color ﬁle.23. gcf Gets the handle of the current ﬁgure.

.1. legend Produces a legend of elements of a plot. print Saves a ﬁgure to disk in a wide range of formats. set Sets a property of a graphics handle.144 Quick Function Reference hist Produces a histogram of data. scatter Produces a scatter plot of x data against y data. pie Produces a pie chart. subplot(2. surf Produces a 3-D surface plot of a matrix of z data against vectors of x and y data. shading Changes the shading method for 3-D ﬁgures.x). Can also be used to compute bin centers and height.2). subplot Command that allows for multiple plots to be graphed on the same ﬁgure. mesh Produces a 3-D mesh plot of a matrix of z data against vectors of x and y data. plot Plots x data against y data. such as subplot(2. Used in conjunction with other plotting commands. plot(y.1.1). plot(x.y). plot3 Plots z data against x and y data in a 3-D setting.

zlabel Produces a text label on the z-axis of a ﬁgure. to MATLAB serial (numeric) dates. datenum Converts string dates. datetick Converts axis labels in serial dates to string labels in plots. xlabel Produces a text label on the x-axis of a ﬁgure. ylabel Produces a text label on the y-axis of a ﬁgure. now Returns the current time in MATLAB serial date format.15 Date Functions 145 title Produces a text title at the top of a ﬁgure.15 clock Date Functions Returns the current date and time as a 6 by 1 numeric vector of the form [YEAR MONTH DATE HOUR MIN SEC]. 23. . such as 1-Jan-2000. date Returns string with current date. datestr Converts serial dates to string dates. datevec Parses date numbers and date strings and returns date vectors of the form [YEAR MONTH DATE HOUR MIN SEC]. etime Can be used to compute the elapsed time between two readings from clock.23.

strcat Horizontally concatenates two or more strings. strcmp Compares two string values using using a case-sensitive comparison.16 char String Function Converts numeric values to their ASCII character equivalents. toc Ends a tic-toc timing loop. 23.146 Quick Function Reference tic Begins a tic-toc timing loop. Flexible but slow. double Converts values to double precision from character or other data types. x2mdate Converts excel dates in the MATLAB serial dates. str2double Converts string numbers to doubles. Equivalent to [string1 string2] for strings with the same number of rows. strcmpi Compares two string values using using a case-insensitive comparison. num2str Converts numbers to strings for output or inclusion in graphics. Useful for determining the amount of time required to run a section of code. Limited but fast. str2num Converts string numbers to doubles. .

strncmp Compares the ﬁrst n characters of two strings using a case-sensitive comparison. changes the working directory to that directory. dir Returns the contents of the current working directory. strvcat Vertically concatenates two or more strings. Operates element-by-element on vectors or matrices.. right pads the shorter string with blanks.17 cos Trigonometric Functions Computes the cosine of a scalar. delete Deletes a ﬁle from the present working directory. vector or matrix. use the function version cd(‘c:\dir with space\dir2\dir3’).18 cd File System Change directory. . strmatch Finds exact string matches. ﬁles deleted are permanently gone and not in the Recycle Bin. When called as cd . Operates element-by-element on vectors or matrices.23..17 Trigonometric Functions 147 strfind Finds substrings in a string. sin Computes the sine of a scalar. If the desired directory has a space. If the strings have different numbers of columns. vector or matrix. strncmpi Compares the ﬁrst n characters of two strings using a case-insensitive comparison. 23. Warning: This command is dangerous. When used with a directory. 23. changes the working directory to its parent.

if ﬁlename. rmdir Removes a child directory in the present working directory. . while clear var1 var2 .m or. format short is the default. doc When used as doc function. format Changes how numbers are represented in the command windows. clear and clear all remove all variables from memory. If called using edit ﬁlename. clf Clears the contents of a ﬁgure window. Child directory must be empty.m does not exist on the MATLAB path. . Can be used to close all ﬁgure windows by calling close all. opens the help browser to the documentation of function. clear Clears variables from memory.148 Quick Function Reference mkdir Creates a new child directory in the present working directory. close Closes ﬁgure windows. opens the editor with ﬁlename.19 clc MATLAB Speciﬁc Clears the command window. creates the ﬁle in the current directory. . pwd Returns the path of the present working directory. format long shows all decimal places while format short only shows up to 5. edit Launches the built-in editor. removes only those variables listed. When used alone (doc) opens the help browser. 23.

keyboard Allows functions to be interrupted for debugging. • profile viewer turns the proﬁles off and opens the proﬁling report which contains statics on the performance on code executed since profile on was called realmax Returns the largest number MATLAB is capable of represented. Larger numbers are Inf. helpbrowser Opens the integrated help system for MATLAB at the last viewed page. Reports code dependencies. helpdesk Opens the integrated help system for MATLAB at the home page. returns full path to function.19 MATLAB Speciﬁc 149 help Displays inline help for calling a function (help function). Does not stop the proﬁler. After verifying function operation. Has four important variants: • profile on turns the proﬁles on • profile off turns the proﬁles off • profile report opens the proﬁling report which contains statics on the performance on code executed since profile on was called. whos Returns a list of all variables in memory along with a description of type and information on size and memory requirements. profile Built-in MATLAB proﬁler. Numbers closer to 0 are 0. Useful if there may be multiple functions with same name on the MATLAB path. . realmin Returns the smallest positive number MATLAB is capable of representing. use return to continue running. timing of executed code and provides tips for improving the performance of m-ﬁles. Also can be used to list the function in a toolbox (help toolbox) or to list toolboxes (help). which When used in combination with a function name.23.

csv ﬁles. csvwrite Saves variables to a . Has been replaced by textscan. Can also be used to save tab delimited text ﬁles.csv ﬁle. returning a string representing the line without the end-of-line character. Can read into cell arrays and from speciﬁc points in a ﬁle.mat) into the current workspace.g. fprintf Writes formatted text to a ﬁle.150 Quick Function Reference 23. Requires all data be numeric. xlsfinfo Returns information about an .20 csvread Input/Output Reads variables in . Can also be used to load simple text ﬁles. load Loads the contents of a MATLAB data ﬁle (. fgetl) or writing (using e. fprintf). fopen Opens a ﬁle for low level reading (using e. textread Older method to read formatted text. Can be combined with -ascii -double to produce a tab delimited text ﬁle. save Saves variables to a MATLAB data ﬁle (.g.xls ﬁle. textscan Reads formatted text. fgetl Reads the current ﬁle until an end-of-line character is encountered. such as sheet names. .mat). fclose Used to close a ﬁle handle opend using fopen.

xlswrite Saves variables to an . although it does contain methods which allow for text to be read.xls ﬁle. . All data should be numeric.23.xls ﬁles.20 Input/Output 151 xlsread Reads variables in .

95 *rnd. 136 ceil. 150 csvwrite. 146 edit.Index . 61. 29. 147 disp. 142 eps. 135 . 143 bar3. . 148 clf. 107. 118–121 char. 140 cd. 123. 143 break. 27. 133 dir. 139 clc. 138 any. 135 csvread. 139 diff. 133 eye.. 31 doc. 141. 148 clock. 31. 137 AND. 148 clear. 108. 145 datetick. 150 cumprod. 140 date. 148 eig. 138 fclose. 145 close. 143 bar. 12 continue. 57. 135 cos. 141 cat. 133 all. 143 etime. 93 dlmwrite. 148 double. 141 end. 147 cdf. 142 case. 137 axis. 139 cumsum. 150 figure. 30. 142 contour. 111. . 148 colormap. 139 else.. 141 elseif. 105. 118 corrcoef. 108. 56 ans. 147 cov. 143 Comments. 12 *cdf. 143 find. 69. 145 datestr. 111. 145 datevec. 95 *pdf. 95 *inv. 137 Cell Arrays. 145 delete. 145 datenum. 57. 143 corr. 108. 138 errorbar. 95 . 62. 61. 134 cell. 13. 10. 68. 79. 150 fgetl. 11 %. 106. 146 chol. 139 diag. 145 exp. 29. 147 det. 12 abs. 27.

144 plot. 135 rand. 134 NaN. 150 log. 142 fmincon. 135 M-Lint. 145 num2str. 138 Performance. 95. 134 mesh. 137 isreal. 136 randg. 136 roots. 83. 143 OR. 38. 144 prctile. 95. 93. 130. 137 random. 143 help. 138 optimget. 87. 28. 148 mod. 139 ischar. 127 pi. 138 intersect. 129 max. 65. 142 fminunc. 138 load. 149 regexp. 143 optimset. 56 otherwise. 140 research. 138 logspace. 134 mkdir. 104. 93 reshape. 149 helpbrowser. 23–31 Inf. 56. 73. 98. 135 repmat. 139 kurtosis. 142 fopen. 140 rmdir. 99. 144 profile. 100. 56 now. 29. 149 realmin. 149 hist. 148 fprintf. 108. 137 keyboard. 62 pdf. 137 isinf. 137 realmax. 99. 136. 134 round. 144 plot3. 140 linspace. 136 Importing Data. 144 if. 131. 140 inv. 149 pwd. 137 isnan. 148 quantile. 142 fminsearch. 138 pie. 78 . 138 NOT. 134 fminbnd. 114 regress. 142 format.INDEX 153 floor. 150 for. 149 helpdesk. 136 randn. 71. 61. 148 rnd. 37. 71. 39. 73–75. 141 min. 134 mean. 135 legend. 131. 140 ones. 146 numel. 133 log10. 114 regexpi. 95. 133 logical. 137 isfinite. 114. 149 kron. 12. 144 length. 150 gcf. 135 print. 143 get.

112. 25. 147 strncmpi. 141 sortrows. 139 type. 147 size. 150 tic. 147 strncmp. 146 strcat. 26. 144 sum. 79. 76. 146 title. 71. 112. 28. 29. 112. 40. 113. 108. 146 strcmp. 146 toeplitz. 145 zeros. 144 setdiff. 71. 150 xlsflinfo. 114. 146 strfind. 38. 75.154 INDEX save. 144 sign. 140 skewness. 139 tril. 134 sin. 141 var. 141 unique. 142 whos. 146 str2num. 113. 146 strcmpi. 24. 113. 144 switch. 71. 136 . 135 sort. 151 ylabel. 117–118 strvcat. 123 union. 39. 147 strmatch. 28. 147 subplot. 149 while. 31. 147 struct. 145 toc. 29. 145 xlsfinfo. 113. 134 surf. 142 textread. 10. 151 xlswrite. 31. 141 sqrt. 145 Structures. 71. 37. 114. 47 zlabel. 138 trace. 136 str2double. 144 set. 108. 30. 25 xlsread. 150 scatter. 67. 150 textscan. 140 shading. 146 xlabel. 62. 113. 139 triu. 149 x2mdate. 134 std. 117 which.

- Read and print without ads
- Download to keep your version
- Edit, email or read offline

Are you sure?

This action might not be possible to undo. Are you sure you want to continue?

CANCEL

OK

You've been reading!

NO, THANKS

OK

scribd

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->