Programming Previous page   Next Page

Creating a Simple M-File

You create M-files using a text editor. MATLAB provides a built-in editor, but you can use any text editor you like. Once you have written and saved the M-file, you can run the program as you would any other MATLAB function or command.

The process looks like this:

Using Text Editors

M-files are ordinary text files that you create using a text editor. If you use the MATLAB Editor/Debugger, open a new file by selecting New -> M-File from the File menu at the top of the MATLAB Command Window.

Another way to edit an M-file is from the MATLAB command line using the edit function. For example,

opens the editor on the file foo.m. Omitting a filename opens the editor on an untitled file.

You can create the fact function shown in Basic Parts of an M-File by opening your text editor, entering the lines shown, and saving the text in a file called fact.m in your current directory.

Once you have created this file, here are some things you can do:

A Word of Caution on Saving M-Files

Save any M-files you create and any MathWorks supplied M-files that you edit in directories outside of the directory tree in which the MATLAB software is installed. If you keep your files in any of the installed directories, your files may be overwritten when you install a new version of MATLAB.

MATLAB installs its software into directories under $matlabroot/toolbox. To see what $matlabroot is on your system, type matlabroot at the MATLAB command prompt.

Also note that locations of files in the $matlabroot/toolbox directory tree are loaded and cached in memory at the beginning of each MATLAB session to improve performance. If you save files to $matlabroot/toolbox directories using an external editor, or if you add or remove files from these directories using file system operations, enter the commands clear functionname and rehash toolbox before you use the files in the current session.

For more information, see the rehash function reference page or the section Toolbox Path Caching in the Desktop Tools and Development Environment documentation.


Previous page  Basic Parts of an M-File Providing Help for Your Program Next page

© 1994-2005 The MathWorks, Inc.