Lesson 1.5

The m-file


  • Understand what a “m-file” is.
  • Learn what and how MATLAB saves in an m-file.
  • Learn the difference between code and a comment.
  • Review the color coding in an m-file.

What Is an m-file?

A m-file is the file type MATLAB uses to store programming code. This is just like Microsoft Word using .doc/.docx file extension. The file extension is (.m): hence m-file.

Figure 1: This is what the m-file will look like in a file explorer (Windows in this case).

There are a few more things you should know about m-files in general, which we will cover in the following sections. Also, note that all of the code examples in this course have m-files, which you can download, review, and run with MATLAB.

What Is Saved in an m-file?

The “stuff” that is saved in your m-file is the MATLAB code you write. For example, the code we wrote in the previous Hello World lesson (LINK TO LESSON). The m-file does not store any outputs (e.g., numbers, text, figures, etc.). Of course, you can always get these outputs by running the code again!

Figure 2: The code written in the editor will be saved in the m-file.

Code vs. Comment

In programming, a comment is some characters that will not be evaluated and executed when your code (program) is run. This has many obvious positive uses relating to writing notes to yourself or others who use the program, organization, and debugging your program, which we will explain more in a later lesson (LINK TO LESSON).

In MATLAB, comments are denoted in MATLAB by a percent sign, %. They will also turn green in the m-file as seen in Example 1 and Figure 2.

Example 1: Demonstrating Comments
% This is a comment. % In MATLAB comments show up as green and are not considered and executed. % The following is a demonstration of the difference between a comment and code. a = 5 % Comments can also be at the end of a line of code, but not in the middle! %b = 1 Command Window Output
Hello World [Try this code yourself with Octave Online! Click Here]

Color Highlighting

By now, you have noticed that MATLAB highlights some text in different colors. In Figure 3, you can see the default color preferences in MATLAB which describes how MATLAB color codes different text. You can see comments are selected as green.

It is ok if you do not know what all of the terms mean (like “strings”) in Figure 3 as we will cover these in later lessons and all examples are color coded appropriately. This is just to introduce you to the idea of color coding in MATLAB. You can find more information on MATLAB’s Color Settings page.

Figure 3: Default color highlighting preferences in MATLAB.

Next Lesson

In the next lesson, we will cover how to use the Command Window effectively.