Creating M-Files

As it was touched on in the Introduction to MATLAB section, MATLAB works with two file types: Scripts and Functions. Both are saved with a .m extension, so they are both M-files. There are several ways to create M-files, and some of those were looked at in the examples of Introducing MATLAB. For completion, those are explained again in detail to give you a full understanding of how they work.


2.1.1 Creating Scripts
There are a couple ways of creating script files, and those are covered in this subsection. You may be wondering what scripts are and why they are needed. Scripts are files that store your code, and without them, you won’t be able to run effective programs that once executed, can perform many tasks. Think of scripts like .doc or .docx documents for Microsoft Word. Microsoft Word serves as an interface for reading and editing .doc or .docx documents.

To create a script from the main MATLAB ribbon, you need to select ‘Create Script’ under the ‘File’ section of the ‘Home’ tab. Alternatively, you could press ‘New’ and select ‘Script’ from the context meu, or you could press Ctrl+N on your keyboard.

To create a script from existing code in the Command History window, you need to highlight the commands that you wish to include in your script (by holding the ctrl key and selecting those that you wish to include), or click on the line to the left of the body of code that you wish to include, right click and select ‘Create Script’ in the context menu. This has been demonstrated in Worked Exercise 1.1.


2.1.2 Creating Functions
A function is a process/procedure that may be used using different input arguments to generate an output, without typing repetitive code over and over again. This saves time, disk space and clutter, which is very advantageous. To create a function, you need to select ‘Function’ instead of ‘Script’ under the ‘New’ context menu of the Home tab.


2.1.3 Other Types of Files
MATLAB does not just deal with M-files; it can edit text files (.txt), create figures (.fig) and many others. Explore the different file types that MATLAB deals by exploring the ‘New’ menu further and by experimenting.