MATLAB is also a powerful programming language, as well as an interactive computational environment.

If you use Matlab command prompt, MATLAB also allows you to write series of commands into a file and execute the file as complete unit, like writing a function and calling it.

The M Files

MATLAB allows writing two kinds of program files −

  • Scripts − script files are program files with .m extension. In these files, you write series of commands, which you want to execute together. Scripts do not accept inputs and do not return any outputs. They operate on data in the workspace.
  • Functions − functions files are also program files with .m extension. Functions can accept inputs and return outputs. Internal variables are local to the function.

You can use the MATLAB editor or any other text editor to create your .mfiles. In this section, we will decide the script files. A script file contains multiple sequential lines of MATLAB commands and function calls. You can run with a script by typing its name at the command line.

Creating and Running Script File

For create scripts files, you need to use a text editor. You can open the MATLAB editor via different ways:

  • Using the command prompt
  • Using the IDE

If you are using the command prompt, type edit in the command prompt. This will open the editor. You can directly type edit and then the filename (with .m extension)

edit <filename>

The above command will create the file in default MATLAB directory. If you want to store all program files in a specific folder, then you will have to provide the entire path.

Let us create a folder named progs. Type the following commands at the command prompt (>>):

mkdir progs    % create directory progs under default directory
chdir progs    % changing the current directory to progs
edit  prog1.m  % creating an m file named prog1.m

If you are creating the file for first time, MATLAB prompts you to confirm it. Click Yes.

matlab editor
Alternatively, if you are using the IDE, choose NEW -> Script. This also opens the editor and creates a file named Untitled. You can name and save the file after typing the code.

Type the following code in the editor −

NoOfStudents = 6000;
TeachingStaff = 150;
NonTeachingStaff = 20;
Total = NoOfStudents + TeachingStaff ...
   + NonTeachingStaff;

After creating and saving the file, you can run it in two ways −

  • Clicking the Run button on the editor window or
  • Just typing the filename (without extension) in the command prompt:>> prog1

The command window prompt displays the result −



Create a script file, and type the following code −

a = 5; b = 7;
c = a + b
d = c + sin(b)
e = 5 * d
f = exp(-d)

When the above code is compiled and executed, it produces the following result −

c =  12
d =  12.657
e =  63.285
f =    3.1852e-06