## Are you sure?

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

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 (-) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16. . . . . . . . . . . . . . . . . . .10 Exercises . . . . . . . 98 . . .5 surf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 datenum . . . . . . . . . . . . .2 prctile . . . . . . . . . .4 scatter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 . . . . . . 15. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 The UCSD_GARCH/MFE Toolbox 15. . . . . . . . . . . . . . . . . *pdf. . . . . . . . . . . . . .2 datestr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 print . . . . . . . . 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16. . . . .4 fmincon . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Other Optimization Routines 17 Dates and Times 17. . . .2 Exercises . . . . . . . . . . . . . . . . . . . .3 regress . . . . . . . . . . . . . 13. . . . . . . . . . . . . . . . *inv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. . . . . . . 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 quantile . . . . . . . . . . . . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 . . . . . . . . . . . .5 optimset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Debugging . . 15. . . . . . . . . . . . . . . . 15. . . . . . . . . . . 12. .2 plot . 12. . . . . . . . . . . . . . .4 *cdf. . . . . . . . . .3 datevec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 now and clock 17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . *rnd. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 . . . . . . . . . . . . . . . . . . . . . . . . . 16. . 16 Optimization 16. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .CONTENTS 5 12 Graphics 12. . . . . . . . . . . 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. . . . . . . . . . . .7 Exercises . . . .6 mesh . . . . . . . 16. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Custom Functions 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . . . . . . . .1 fminunc . . . . . . . . . 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 . . .9 Advanced Graphics 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 subplot . . . . . . . . . . . . . . . . . . 12. . . . . . . . . . . . . . . . . . . . . . . 100 . . . . . . . 15. . . . . . . . .2 fminsearch . . . . . . . .3 Exercises . . . . . . . . . . . .1 Comments . . . . . . . . . . .6 The JPL Toolbox . . . . . . . . . 16. . . . . . . . . . . . . . . . . 15.3 plot3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 105 105 106 107 108 108 . . . . . . . . . . . 12. . 15 Probability and Statistics Functions 15. . . . . . . . . . . . .1 Support Functions 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 tic and toc . . .3 fminbnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 contour . . . . . . . . . . . . . . . .

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

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

8 CONTENTS .

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

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

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

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

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

14 Introduction to MATLAB .

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

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

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

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

:) ans = 1 >> x(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. will return the elements from x in rows 1 and 2 and columns 1 and 2.1) ans = 1 >> x(1. is interpreted as all elements from matrix x in column 1.2. When used.:) will returns all columns from rows 1 and 2 of x. Similarly. x(:. x(2. in which case the indices correspond directly to the order of the elements in x. vectors can be used to access elements of x.1).2) ans = 2 >>x(1. Double indexing of matrices is available using the notation x(#. For instance. Double : notation produces all elements of the original matrix and so x(:. The colon operator (:) plays a special role in accessing elements.2. >> x(1. #. x([1 2].3) ans = 3 >> x(2.:) 2 3 . #). while x([1 2]. >> x(1.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.1) ans = 4 >> x(3. Finally.:) returns x.[1 2]). x(1. x(#. it is interpreted as all elements in that dimension.:) is interpreted as all elements from x in row 2.#).3) would return the element in the ﬁrst row of the second column of the third panel of a 3-D matrix x. For instance. For example.

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

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

22 Basic Input .

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

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

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.

some data is only available in formats where reading in data line-by-line is the only option. end %Close the file fclose(fid).txt). 2001. Reading poorly formatted data ﬁles is an advanced technique and should be avoided if possible.6 MATLAB Data Files (. %Pre-allocate the data dates = zeros(count-1.1).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.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. 3. textread can handle a variety of data formats. 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. if ~ischar(line) break end count=count+1. See doc textread for further information. The standard command is textread which has a syntax similar to xlsread.mat) The native ﬁle format is the MATLAB data ﬁle.2001 through January 31. For instance. the only possibility is to write a program to read the ﬁle line-by-line and to process each line separately.5 Text Reading in text is also simple if the ﬁle only contains numbers. the standard import method fails if the raw data is very large (too large for Excel) and is poorly formatted. fid=fopen(’IBM_TAQ. textread has been updated in the function textscan which can read both numeric and string data. The ﬁle IBM_TAQ. dates and text on each line. Data from a mat ﬁle is loaded by entering load deciles.txt’). %Count number of lines count=0. However. In this case.’rt’).mat There is no need to specify an input variable as the mat ﬁle contains both variable names and data. or mat ﬁle. It is too large to use in Excel and has both numbers. See below for saving data in mat format. 3. while 1 line=fgetl(fid). .28 Importing and Exporting Data 3. data = textread(’deciles.txt’. The following code block shown how the data in this ﬁle can be parsed.

’. %Get one line to throw away since it contains the column labels line=fgetl(fid). price = zeros(count-1. 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. %while 1 and break work well when reading test while 1 line=fgetl(fid). %Increment the count count=count+1. %Use count to index the lines this pass count=1.’). minutes or and seconds to numbers hour=str2double(temptime(1:colons(1)-1)). %Reopen the file fid=fopen(’IBM_TAQ. %Dates are places between the first and second commas dates(count)=datenum(line(commas(1)+1:commas(2)-1). second=str2double(temptime(colons(2)+1:length(temptime))). so they need further parsing colons=strfind(temptime.’rt’). %Times are between the second and third temptime=line(commas(2)+1:commas(3)-1).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 .’yyyymmdd’). %Convert these values to seconds past midnight time(count)=hour*3600+minute*60+second.1). end fclose(fid). %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)).txt’.3. %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.7 Manually Reading Poorly Formatted Text 29 time = zeros(count-1. %Convert the text representing the hours. %Times are colon separates. they delimit the file commas = strfind(line. minute=str2double(temptime(colons(1)+1:colons(2)-1)).

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. data = textscan(fid. ’delimiter’. 1) fclose(fid). dlmread. IBM_TAQ. The data read in by textscan is returned as a cell array. . fread. For more on reading poorly formatted data ﬁle. and textscan. The use of curly braces. >> 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. fid = fopen(’IBM_TAQ.8 Reading Poorly Formatted Text Using textscan textscan is a fast method to read ﬁle that contain mixed numeric and string data. fgetl.csv’).txt is satisﬁes these two constraints and so can be read using the command block below. First. 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. ’%s %f %s %f %f’. see the documentation for fopen.’. that the columns are delimited by a comma. and second each row must contain the same type of data – that is the ﬁle must not mixing strings with numbers in a column. and that the ﬁrst line is a header and so should be skipped. fscanf. ’.30 Importing and Exporting Data • Closes the ﬁle directly using fclose 3. the ﬁle must be regular in that it has the same number of columns in every row. 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. {} indicates that cell array are being used. ’HeaderLines’. See chapter 18 for more on string manipulation.

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

32 Importing and Exporting Data .

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

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

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

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

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

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

If x is a vector. 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).j)=exp(x(i. i = 1. sort To sort the values of a vector or the rows of a matrix from smallest to largest. K use the command max(x).j)). .3891 148.5982 7. If x is a vector. . max(x) is a K by 1 vector containing the maximum values of each column. If x is a matrix. max x i t . use the command sort(x). If x is a matrix. >> x=[1 5 2. z=exp(x) returns a vector or matrix the same size as x where z(i. >> x=[1 2 3. max(x) is scalar.39 max To ﬁnd the maximum element of a vector or the rows of a matrix.4288 2 5 3 6 . ex use exp. sort(x) is vector where x(1)=min(x) and x(i)≤x(i+1). sort(x) is a matrix of the same size where each column is sorted from smallest to largest. 2. .0855 403.7183 54. 4 5 6] x = 1 4 >> exp(x) ans = 2.4132 20. .

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

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

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

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

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

6. Create a custom logspace using the natural log (base e ) rather than the logspace created in base 10 (which is what logspace uses).01. N) is the same as 10.1. . . standard deviation. Using both the : operator and linspace. upper. Repeat exercise 1 on this matrix. Create a new matrix.1544 4. variance. .4) ans = 1.0000 2. Create a new variable SP500sort which contains the sorted values of this series. .99. Hint: Use linspace AND exp. 2. upper.1 Exercises 1.0000 5. Compute the mean of returns’. 4.1 Exercises 45 logspace logspace produces points uniformly distributed in log10 space.5. logspace(lower. Find the max and min of the variable SP500 (see the Chapter 3 exercises). 3.∧ linspace(lower.02. 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. skewness and kurtosis of both returns (SP500 and XOM). 0. returns = [SP500 XOM]’. N). create the sequence 0.6416 10. 5. . 1. Load the MATLAB data ﬁle created in the Chapter 4 exercises and compute the mean. 0. . >> logspace(0.

46 Basic Functions .

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

48 Special Matrices .

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

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

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

52 Matrix Functions .

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

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

. Logical operators. For instance. vector or matrices. >=. end blocks) which will be discussed later. will be a matrix of the same size as x and y composed of 0s and 1s. suppose x and y are matrices. suppose z = x L y where L is one of the logical operators above such as < of ==. 9. if one is scalar. For instance. Alternatively. say y. <=.1 >. All comparisons are done element-byelement and return either 1 (logical true) or 0 (logical false). .j)=(x(i. allow for complex choices to be compactly expressed. when combined with ﬂow control. . <. 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. The following table examines the behavior when x and/or y are scalars or matrices. .. . Logical operators can be used to access elements of a vector or matrix.j)<y).Chapter 9 Logical Operators and Find Logical operators are useful when writing batch ﬁles or custom functions. then the elements of z are z(i. else . 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 . == . ∼= 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. z=(x<y).

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

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

j] = find (x < y) will return pairs of matrix indices what correspond to the places where x<y. .numel(x)) while [i. indices = find (x < y) will return indices (1.6 is* A number of special purpose logical tests are provided to determine if a matrix has special characteristics..2. >> x = [1 2 3 4].j] = find(y) i = 1 2 1 j = 1 1 2 1 0 >> find(y) 9.58 Logical Operators and Find ans = 1 0 >> any(y) ans = 1 1 9. >> y = x<=3 y = 1 1 ans = 1 2 3 >> [i. These functions all begin with is. >> y = x<=2 y = 1 1 0 0 >> find(y) ans = 1 2 >> x = [1 2 . find is not logical itself. . 3 4].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. There are two primary ways to call ﬁnd. but it takes logical inputs and returns matrix indices where the logical statement is true.

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

60 Logical Operators and Find .

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

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

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

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

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

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

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

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

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

Simulate a ARMA(1.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. 4.1)-GJR-GARCH(1. α = 0.9.1)-in-mean process.02 γ = 0.07 and β = 0.03. 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. Hint: keep track of the upper and lower bounds of the random variable value and use ﬂow control.1.05. 3. A GJRGARCH(1. This problem requires normcdf. Test out the loop using by ﬁnding the inverse CDF of 0. Using a while loop.70 Loops 2. Simulate a GARCH(1. α = 0.1) process where εt are independent standard normal innovations. 6. Verify it is working by taking the absolute value of the difference between the ﬁnal value and the value produced by norminv.05.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. Simulate a GJR-GARCH(1. A GARCH(1.1. . write a bit of code that will do a bisection search to invert a normal CDF. I [εt −1 <0] is an indicator variable that takes the value 1 if the expression inside the [ ] is true.1) process where εt are independent standard normal innovations. -3 and pi. A bisection search cuts the interval in half repeatedly. 5. Hint: Some form of logical expression is needed in the loop.4 and λ = 0.05 and β = 0. θ1 = 0.9.

) . legend takes as many strings as unique plot elements.format1 . Standard usage is xlabel(’X Data Name’). 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.format2 }.2 plot plot is the most basic plotting command.y1. These four are the most important support functions. ylabel and zlabel produce text labels on the x .Chapter 12 Graphics Extensive plotting facilities capable of producing a virtually limitless range of graphical data representations are available. . y and z –if the plot is 3-D – axes respectively.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. 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. To retrieve the current axis limits. the most straight forward is plot(x1.x2. 12. • legend labels the various elements on a graph. • title places a title at the top of a ﬁgure. Like most commands.. Standard usage is title(’Figure Title’). • axis can be used to both get the axis limits and set the axis limits.. it can be used many ways.’Series 2’) where the number of series is ﬁgure dependent.y2. Standard usage is legend(’Series 1’. enter AX = axis(). Remember to fully label plots so others can clearly tell which series are being plotted and the units of the plot. This chapter will emphasize the basics of the most useful graphing tools. However. The speciﬁc behavior of legend depends on the type of plot and the order of the data. . 12. • xlabel.9). 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. but there are many additional functions available to tweak ﬁgures (see section 12.

x = linspace(0. Suppose the following x and y data were created.1.y3.y2. .y1.’kp--’) will produce the plot in ﬁgure 12. 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 : -. If no format string is provided. y1 = 1-2*abs(x-0. y3 = 1-4*abs(x-0. y2 = x.^2. 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). an automatic color scheme will be used with marker-less solid lines. use the format string ’g:’. -(none) solid dotted dashdot dashed no line The three arguments are combined to produce a format string.’.5).5).x.100). Calling plot(x. Always use physical characteristics to distinguish multiple series – either different line types or different markers.’rs:’. A line’s color information is lost when documents printed are in black and white.1. For instance.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.x. or both. Arguments which are not needed can be left out.’bo-.

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

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

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

y = linspace(-2.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. pdf was created with the following code: N = 100. was chosen Σ= 2 0.2. This line was plotted by calling scatter(x(:.5 0. the covariance matrix.2).1). 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.x(:.5.5 A matrix of pdf values. x = linspace(-3.5 surf The next three graphics tools all plot a matrix of z data against vector of x and y data. This plot contains a scatter plot of a bivariate normal random deviations with unit variance and correlation of 0.3. Σ.N).4: Scatter plot.N). 12.5 0.N).’rs’). All three uses the results from a bivariate normal probability density function. .. pdf=zeros(N.

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

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

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

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

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

10: Handle graphics. . The top subplot is a standard call to plot while the bottom highlight some of the possibilities when using handle graphics.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. It is worth nothing that all of these changes evidenced in the bottom subplot can be reproduces using the point-and-click method.

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

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

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

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

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

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

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

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

*inv .2 prctile prctile is identical to quantile except it expects an argument from 0 to 100 rather than an argument between 0 and 1. including • χ 2 (chi2-) • β (beta-) • Exponential (exp-) • Extreme Value (ev-) • F (f-) . random number generators and inverse CDFs. its function is simple and can easily be re- placed using sort. *rnd. 15. 15.4 *cdf. PDFs. However. length and floor or ceil. The most valuable code in the statistics toolbox are the CDFs. 15. 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.1 quantile quantile returns the empirical quantile of a vector. *pdf.Chapter 15 Probability and Statistics Functions The statistics toolbox contains an extensive range of statistical function.3 regress regress performs basic regression and returns key regression statistics. All common distributions have the complete set of four provided. 15.

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

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

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

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

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

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

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

Active inequalities (to within options.999936 0.00127 2.95 -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.0004091 0.16.5291.0001502 1.5].34e-005 1.982 0.prices.exitflag]=fmincon(’budget_line’.999936 constraint -0. .615e-007 2.[].31e-008 Line search steplength Directional derivative First-order optimality 0 -1 >> b=[0.451e-005 0.083 0.000283 3. require x1>=0 and x2>=0 A = -1 0 b = 0 0 >> Ubar = . most are problem class speciﬁc so general rules are hard to derive.1. 0] Optimization terminated: first-order optimality measure less than options. options. Note: Many aspects of constrained optimization (and optimization in general) are more black magic than science.[]. 0 -1] %Note.999653 0. >> [x.952732 0.000184 0.Ubar) Max Iter F-count 0 1 2 3 4 5 6 3 6 10 13 16 19 22 f(x) 3 1.9709 6..6666 fval = 0.535e-011 1 0.fval.[].4 fmincon 103 >> A = [-1 0.lambda. Worse.TolFun and maximum constraint violation is less than options..A. Practice is the only way to become proﬁcient at function minimization.TolCon.3333 0.x0.TolCon = 1e-006): lower x = 0.0467 0.[].b.999469 0.5.5 1 1 1 1 -1.05e-007 0. many of the starting values should produce similar parameter estimates and fvals.199 0.02503 0.’compensated_utility’. since -1.0365 0.05238 0.9999 exitflag = 1 upper ineqlin ineqnonlin 1 These two examples are problems where the answers can be analytically veriﬁed. In many cases it is impossible to verify that the global optimum has been found if there are local minima. If the optimizer is working well on the speciﬁed problem.5+1<0 (-u+ubar). >> x0 = [1.. %Start with all constraints satisfied.

) For example. see doc optimset.’option2 ’.1e-3).1000.5 optimset optimset sets optimization options and has two distinct forms. Once the options structure has been initialized. The initial call to optimset should always be of the form options = optimset(’fmintype’) which will return the default options for the selected optimizer. For help on the available options or their speciﬁc meaning.’MaxFunEvals’. 16..6 Other Optimization Routines The Optimization toolbox contains a number of other optimization algorithms: fseminf Multidimensional constrained minimization.’TolFun’. 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 . individual options can be changed by calling options = optimset(options.104 Optimization 16.option value2 . >> options = optimset(’fmincon’).option value1 .’option1 ’.1000). >> options = optimset(options. >> options = optimset(options. . to set options for fmincon.’MaxIter’. .

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

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

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

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

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

These two arguments ensure datetick behaves sanely.’keeplimits’). . set up the ﬁgure as is should look but with serial dates.’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. and then call datetick(’x’.2: datetick with keepticks and keeplimits. To use them.

Chapter 3 contains an example of parsing a poorly formatted ﬁle. Since character data are contained in matrices. >> char(65:100) ans = ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_‘abcd >> char([1.32 pi 256]) ans = double double changes character strings into their numerical values.Chapter 18 String Manipulation While manipulating text is not MATLAB’s forté. However. The primary application of string functions is to parse data. 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.’. >> double(’MATLAB’) ans = 77 97 116 108 97 98 . using commands designed for numerical data is tedious and special purpose functions are provided to assist with string data. they respect the standard behavior of most commands (e.g. Other values produce a nonsense result. It uses a number of string functions to manipulate and parse the text of a ﬁle. str(1:10)). Strings are treated as matrices of character data.

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

’beta’.5) ans = 0 >> strncmpi(’apple’. It is case sensitive. To match only the entire row.’Apple1’.113 ababababa >> strfind(str. >> strmatch(’alpha’.’apple1’. strcnmpi does the same but is not case sensitive. >> strncmp(’apple’. strcmpi does the same but is not case sensitive.5) ans = 1 >> strncmp(’apple’.str) ans = 1 .’a’) ans = 1 >> strcmp(’a’.’A’) ans = 1 strncmp and strncmpi strncmp compares the ﬁrst n characters of two strings and returns (logical) 1 if they are the same. use the optional command ’exact’ >> str = strvcat(’alpha’.’Apple1’. >> strcmp(’a’.’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.’A’) ans = 0 >> strcmpi(’a’.’alphabeta’).6) ans = 0 >> strncmp(’apple’.’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.

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

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

116 String Manipulation .

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

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

After the string vector ’cell’ was added in the ﬁrst position.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.1) cellArray = ’string’ [1x5 double] {2x1 cell } .2 Cell Arrays 119 % Initialize a cell array >> cellArray = cell(2. as the next example shows. >> 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.1). the string vector ’array’ was placed into the second position. Finally. Cell arrays are also adept at handling mixed data. % Initialize a cell array >> cellArray{3} = cell(2. only the second was empty. % Initialize a cell array >> cellArray = cell(2.19. and so can be used to store virtually any data structure by nesting. 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). Cell arrays can even contain other cell arrays.

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

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

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

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

126 File System and Navigation .

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

end for i=0:1 y(t) = y(t) + parameters(5-i)*epsilon(t-i).1 + .8εt −1 + εt epsilon = randn(10000.1). consider the following code: y = zeros(100000. For an example of the penalty. parameters = [.2 . 21.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. end end . end. consider the two implementations of the following recursion y t = . toc Elapsed time is 0.014133 seconds.023440 seconds.1 . tic for t=3:10000 y(t) = parameters(1). To see the effects of pre-generating random numbers. e=randn(100000. y(i) = y(i-1) + e(i). y = zeros(100000.8 1]. end 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)]’.5y t −1 − .128 Performance and Code Optimization The second version with a pre-allocated y is 80 times faster. tic. y = zeros(10000. The gain in this case is 30%.011111 seconds.for i=2:100000.1).1). y(i) = y(i-1) + randn. tic.2y t −2 + 0.5 -. This abstraction comes at the cost of performance and memory allocation is slow. end.1). for i=1:2 y(t) = y(t) + parameters(i+1)*y(t-i).1). for i=2:100000. toc Elapsed time is 0.

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

130 Performance and Code Optimization 21. The second run the code to be proﬁled. 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. . 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.6 Proﬁle Code to Find Hot-Spots The ﬁnal and most advanced optimization tool is the proﬁler.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Does not stop the proﬁler. realmin Returns the smallest positive number MATLAB is capable of representing. which When used in combination with a function name. Numbers closer to 0 are 0. • 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. Useful if there may be multiple functions with same name on the MATLAB path. profile Built-in MATLAB proﬁler. 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).19 MATLAB Speciﬁc 149 help Displays inline help for calling a function (help function). 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. use return to continue running. Reports code dependencies. . After verifying function operation. Larger numbers are Inf. whos Returns a list of all variables in memory along with a description of type and information on size and memory requirements.23. helpdesk Opens the integrated help system for MATLAB at the home page. keyboard Allows functions to be interrupted for debugging. helpbrowser Opens the integrated help system for MATLAB at the last viewed page. returns full path to function.

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

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

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

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

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

- NIOS_CSV_Ref_6.2
- maths
- Upload Manual Bulk Payments_040216
- Graphics2-MathsPrelim
- 1431 Training Manual on Spatial Analysis of Plant Diversity and Distribution.final
- e_bgisdnman
- Matlab Imaging Tutorial
- Moving Data From Access to SPSS
- mvm
- ix Bipartite Arrears Calculator - Officers-Ver1.02
- Intro Tom at Lab
- MDM4U Textbook
- Matlab Guide
- Applied Linear Algebra
- MATLAB
- Excel 2007 Lesson 8 Quiz
- Manual Excel Componentone
- Ibm Placement Papers
- CBSE-2013-SP-I.pdf
- Paper 23-ZeroX Algorithms With Free Crosstalk in Optical Multistage Interconnection Network
- Converting ACT to Sales Force
- SELECCIÓN DE MODELOS, PARÁMETROS GENÉTICOS Y TENDENCIAS GENÉTICAS EN LAS EVALUACIONES GENÉTICAS NACIONALES DE BOVINOS BRANGUS Y SALERS
- Containers XLS C04 MS13
- VR10-UG-ECE
- Mat Lab Tutorial
- IITJAM Mathematics syll.docx
- Linear Algebra Complete Book
- IITJEEPCM
- Multinomial Points
- Assignment IT Final

Skip carousel

- tmp8BC6
- UT Dallas Syllabus for math2333.001.10s taught by (axe031000)
- tmpED85.tmp
- AHP technique a way to show preferences amongst alternatives
- UT Dallas Syllabus for math2418.001.07s taught by Paul Stanford (phs031000)
- UT Dallas Syllabus for math2333.503.10s taught by Paul Stanford (phs031000)
- Diacetyl and acetyl propionyl testing on Suicide Bunny (Sucker Punch and Mother's Milk)
- UT Dallas Syllabus for math6319.501 05f taught by Viswanath Ramakrishna (vish)
- tmpA453.tmp
- Tmp 3008
- tmp4D3F.tmp
- Computer Oriented Numerical Methods
- bls_2086_1981_v1.pdf
- Solving Fuzzy Matrix Games Defuzzificated by Trapezoidal Parabolic Fuzzy Numbers
- Aerodynamics
- tmpCA93.tmp
- Modeling To Predict Cutting Force And Surface Roughness of Metal Matrix Composite Using ANN
- tmp939A.tmp
- UT Dallas Syllabus for math2418.001.07f taught by Paul Stanford (phs031000)
- tmpD29D.tmp
- UT Dallas Syllabus for math2333.501.08s taught by Paul Stanford (phs031000)
- tmp9363.tmp
- De Acc Aprltr 2015b
- tmp2059.tmp
- UT Dallas Syllabus for math2418.001.08f taught by (xxx)
- tmp51FA.tmp
- tmp65C0.tmp
- UT Dallas Syllabus for math2333.502.07s taught by Paul Stanford (phs031000)
- tmp9649.tmp
- Tmp 3384

Sign up to vote on this title

UsefulNot usefulClose Dialog## Are you sure?

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

Close Dialog## This title now requires a credit

Use one of your book credits to continue reading from where you left off, or restart the preview.

Loading