Skip to content

MATLAB - M-Files

MATLAB - Program Files: Scripts and Functions

Section titled “MATLAB - Program Files: Scripts and Functions”

While the MATLAB Command Window is excellent for interactive calculations, real power comes from creating reusable programs. In MATLAB, this is done by writing your code into files. This allows you to build complex, automated, and shareable workflows.

This chapter introduces the fundamental building blocks of MATLAB programming: script files and function files.

MATLAB supports several types of program files, each with a specific purpose:

  • Scripts (.m files): A script is a simple list of MATLAB commands. When you run a script, it’s like typing those commands into the Command Window one by one. Scripts operate on data in the main workspace (the ‘base’ workspace).
  • Functions (.m files): Functions are more structured and powerful. They accept specific inputs and produce specific outputs. Crucially, they have their own private workspace, which prevents them from accidentally modifying variables in your main workspace. This makes them robust and reusable.
  • Live Scripts (.mlx files): A modern format that combines code, formatted text, equations, and visualizations in a single, interactive document. Ideal for exploration, teaching, and creating reports.
  • Classes (.m files): For advanced, object-oriented programming to create custom data types and complex applications.
  • Apps (.mlapp files): Created with App Designer, these files contain the code for building interactive graphical user interfaces (GUIs).

We will focus on the two most common types: scripts and functions.

To create a script, you use the MATLAB Editor. You can open the editor and create a new script file named my_script.m by typing:

edit my_script.m

If the file doesn’t exist, MATLAB will prompt you to create it. This opens the Editor window. Alternatively, you can click the New Script button on the HOME tab of the MATLAB toolbar.

Let’s create a script that generates a sine wave, calculates its average value, and plots the result.

Type the following code into the editor and save the file as analyze_wave.m:

% analyze_wave.m
% This script generates and analyzes a simple sine wave.
% 1. Define parameters
Fs = 1000; % Sampling frequency in Hz
T = 1/Fs; % Sampling period in seconds
L = 1500; % Length of signal
t = (0:L-1)*T; % Time vector
frequency = 50; % Frequency of the sine wave in Hz
% 2. Generate the signal
signal = sin(2 * pi * frequency * t);
% 3. Perform analysis
mean_val = mean(signal);
% 4. Display results and plot
figure; % Create a new figure window
plot(t(1:100), signal(1:100)); % Plot only the first 100 points
title('Sine Wave Signal');
xlabel('Time (s)');
ylabel('Amplitude');
fprintf('The mean value of the signal is: %.4f\n', mean_val);

To run the script, either click the Run button in the Editor, or type the script’s name (without the .m extension) in the Command Window:

analyze_wave
% --- Output in Command Window ---
% The mean value of the signal is: -0.0000
% A plot window will also appear.

Important Note: All variables created by the script (Fs, t, signal, etc.) now exist in your base workspace. Running another script could accidentally overwrite them.

Functions are the key to writing clean, reusable, and maintainable code. They are self-contained modules that perform a specific task.

A function must be saved in a file with the same name as the function. For a function named myFunction, the file must be myFunction.m.

function [outputArg1, outputArg2] = myFunction(inputArg1, inputArg2)
%MYFUNCTION A one-line summary of what the function does (H1 line).
% A more detailed explanation of the function, its inputs, and its
% outputs can go here. This text appears when you type 'help myFunction'.
% Function body: code to calculate outputs from inputs
outputArg1 = ...;
outputArg2 = ...;
end % The 'end' keyword is required for function files.

Example: A Celsius to Fahrenheit Converter

Section titled “Example: A Celsius to Fahrenheit Converter”

Let’s create a function to convert temperature from Celsius to Fahrenheit. Create a new file named celsiusToFahrenheit.m and enter the following code:

% In file celsiusToFahrenheit.m
function fahrenheit = celsiusToFahrenheit(celsius)
%CELSIUSTOFAHRENHEIT Converts temperature from Celsius to Fahrenheit.
% F = CELSIUSTOFAHRENHEIT(C) converts the temperature C in degrees
% Celsius to F in degrees Fahrenheit.
% Apply the conversion formula
fahrenheit = (celsius * 9/5) + 32;
end

Now you can call this function from the Command Window like any built-in MATLAB function:

boiling_point_F = celsiusToFahrenheit(100)
boiling_point_F =
212
freezing_point_F = celsiusToFahrenheit(0)
freezing_point_F =
32

Notice that the variables celsius and fahrenheit inside the function do not appear in your base workspace. Their scope is local to the function.

  • MATLAB Projects: For any non-trivial work, use MATLAB Projects (.prj). A project helps you organize your files, manage required paths, integrate with source control, and easily share your work with others.
  • Source Control: The MATLAB Editor has built-in integration with Git and Subversion (SVN). You can commit, pull, push, and manage branches directly from the MATLAB IDE, which is essential for collaborative work and tracking changes.