7. M-Files
Society for Industrial and Applied Mathematics eBooks · 2005
7.1. Scripts and Functions Although you can do many useful computations working entirely at the MATLAB command line, sooner or later you will need to write M-files. These are the equivalents of programs, functions, subroutines, and procedures in other programming languages. Collecting together a sequence of commands into an M-file opens up many possibilities, including • experimenting with an algorithm by editing a file, rather than retyping a long list of commands, • making a permanent record of a numerical experiment, • building up utilities that can be reused at a later date, • exchanging M-files with others. Many useful M-files that have been written by enthusiasts can be obtained over the internet; see Appendix C. An M-file is a text file that has a .m filename extension and contains MATLAB commands. There are two types: Script M-files (or command files) have no input or output arguments and operate on variables in the workspace. Function M-files contain a function definition line and can accept input arguments and return output arguments, and their internal variables are local to the function (unless declared global). A script enables you to store a sequence of commands that are to be used repeatedly or will be needed at some future time. A simple example of a script M-file, marks.m, was given in Section 2.1. As another example we describe a script for playing “eigenvalue roulette” [23], which is based on counting how many eigenvalues of a random real matrix are real. If the matrix A is real and of dimension 8 then the number of real eigenvalues is 0, 2, 4, 6, or 8 (the number must be even, since nonreal eigenvalues appear in complex conjugate pairs).