Open In App

M – Files in MATLAB

MATLAB provides a feature to store a sequence of statements in a file and execute these statements at the MATLAB prompt exactly as if have typed each command sequentially. Such files are called M-files or script files because they contain file extensions as ‘.m’. M-files are basically text files where we can place our MATLAB commands. These files can be created using any word processing function or any editor. If we have two m-files with the same name, then MATLAB will execute the statements from the file that appears first in the path order. M-files will be very productive and efficient as well as time-saving.  

Types of  M-files :

Script files: It is an external file comprising a sequence of MATLAB statements with the file extension ‘.m’. These files are also known as M-files. To execute the statements in the file, type the name of the m-file at the MATLAB prompt. The variables in a script file are global which allows modification in the value of variables of the same name in the environment of the current MATLAB session. M-files neither accept any input nor do they return any output rather they operate on data in the workspace.



Function files: Functions are subprograms in the main program that perform a specific task. Functions are M-files that accept input and return output. Make sure that the name of M-files and functions should be the same.  Variables in a function file are local by default, but we can declare a variable global.

Methods to Create M-file:

Method 1: Creating M-file using MATLAB editor :



Example:




% MATLAB code for M-file demo
Students = 1500;
Teachers = 20;
Helpers = 15;
TicketPrice = 500;
  
TotalAmount = (Students + Teachers  + Helpers)*TicketPrice;
fprintf(TotalAmount);

>> program1: 767500

Method 2: Creating M-file using Command Window:

 

Example: 




% MATLAB code to create
% M-file using Command Window
a = 20;
b=50;
c=100;
average=(a+b+c)/3;
fprintf(average);

Output:

>> program2
   56.6667

Method 3: Creating M-file using Live Editor:

 

Example: 




% MATLAB code to create M-file
% Using Live Script
a = 20;
b=50;
c=100;
average=(a+b+c)/3;
fprintf(average);

Output:

56.6667

Article Tags :