Introduction: The Architecture of MATLAB Programs
If you’ve been following this course from the beginning, you’ve already encountered both script files and function files. You know that scripts are simple sequences of MATLAB commands that execute in the base workspace, and functions are more structured programs that take inputs, produce outputs, and have their own local workspace.
But there’s so much more to MATLAB programming than these basics. In this comprehensive guide, we’re going to dive deep into the architecture of MATLAB programs. We’ll explore the different types of functions (primary, subfunctions, nested, private), unravel the mysteries of variable scope (local, global, persistent), master function handles and anonymous functions, and learn how to write robust, production-quality MATLAB code with input validation and defensive programming.
This isn’t just a “how-to” guide. We’re going to explore the why behind MATLAB’s design decisions. Why does MATLAB have both scripts and functions? Why are global variables considered harmful? What are the performance implications of nested functions? How does the function call stack actually work? By the time you finish this article, you won’t just know how to write MATLAB functions—you’ll understand the deep architectural principles that make MATLAB both powerful and, at times, perplexing.
Script Files: When and How to Use Them Properly
We introduced script files in Article 03, but we barely scratched the surface. Let’s dive deeper into the proper use of scripts, their limitations, and the best practices for writing maintainable script code.
The Anatomy of a Script File
A script file is simply a file with a .m extension that contains a sequence of MATLAB commands. When you run a script, MATLAB executes those commands in the base workspace.
Here’s a well-written script (analyze_data.m):
%% analyze_data.m
% A script to load, process, and visualize experimental data.
% This script expects a file named 'experiment_data.mat' in the current directory.
% --- Step 1: Load the data ---
if ~isfile('experiment_data.mat')
error('File experiment_data.mat not found. Please ensure it is in the current directory.');
end
load('experiment_data.mat', 'data', 'sample_rate', 'channel_names');
% --- Step 2: Preprocess the data ---
% Remove DC offset (subtract the mean from each channel)
data_processed = data - mean(data, 2);
% Apply a low-pass filter (4th order Butterworth, cutoff at 50 Hz)
[b, a] = butter(4, 50/(sample_rate/2));
data_filtered = filtfilt(b, a, data_processed')';
% --- Step 3: Compute statistics ---
num_channels = size(data, 1);
rms_values = zeros(num_channels, 1);
peak_values = zeros(num_channels, 1);
for ch = 1:num_channels
rms_values(ch) = rms(data_filtered(ch, :));
peak_values(ch) = max(abs(data_filtered(ch, :)));
end
% --- Step 4: Create visualization ---
figure('Name', 'Data Analysis Results', 'Color', 'white');
% Plot 1: Time-domain signals (first 3 channels)
subplot(2, 2, 1);
t = (0:size(data_filtered, 2)-1) / sample_rate;
plot(t, data_filtered(1:min(3, num_channels), :)');
xlabel('Time (s)');
ylabel('Amplitude');
title('Time-Domain Signals (First 3 Channels)');
legend(channel_names{1:min(3, num_channels)}, 'Location', 'best');
grid on;
% Plot 2: RMS values
subplot(2, 2, 2);
bar(1:num_channels, rms_values);
xlabel('Channel');
ylabel('RMS Amplitude');
title('RMS Values by Channel');
set(gca, 'XTick', 1:num_channels, 'XTickLabel', channel_names);
xticklabels(rotateXTickLabels(gca, 45));
grid on;
% Print summary statistics
fprintf('=== Data Analysis Summary ===\n');
fprintf('Number of channels: %d\n', num_channels);
fprintf('Sample rate: %.1f Hz\n', sample_rate);
fprintf('Recording duration: %.2f s\n', size(data, 2)/sample_rate);
fprintf('\n');
for ch = 1:num_channels
fprintf('Channel %d (%s): RMS = %.4f, Peak = %.4f\n', ...
ch, channel_names{ch}, rms_values(ch), peak_values(ch));
end
This script illustrates several best practices:
- Use sections (cells): The
%%syntax divides the script into sections that can be executed independently (using Ctrl+Enter). This is invaluable for rapid prototyping. - Comment extensively: Every step is commented. The comments explain why, not just what.
- Check preconditions: The script checks if the data file exists before trying to load it. This is defensive programming.
- Use meaningful variable names:
data_processed,data_filtered,rms_values—you can infer what these variables contain just from their names. - Create publication-quality plots: The
figure()call sets the background to white (better for printing), and the plots have proper labels, titles, and legends.
When to Use Scripts: A Decision Framework Revisited
We provided a decision framework in Article 03, but let’s refine it with more nuance.
Use a SCRIPT when:
- You’re doing interactive data analysis: You’ve just collected data from an experiment, and you want to explore it. A script lets you modify parameters and re-run sections quickly.
- The task is a “one-off”: You need to convert a bunch of files from one format to another. You’ll never need to do this again. A script is fine.
- You need to share your work with a non-MATLAB colleague: You can send them the script, and they can run it section by section, seeing the output at each step.
DON’T use a SCRIPT when:
- You need to reuse the code: If you find yourself copying and pasting code between scripts, that code should be in a function.
- You’re building a large project: Scripts don’t scale. They pollute the base workspace, they can’t be easily parameterized, and they’re hard to debug.
- You need to pass data between different parts of your code: Scripts communicate through the base workspace (global variables, essentially). This is a maintenance nightmare. Use functions and pass arguments instead.
The “Script as Main” Pattern
A common pattern in MATLAB programming is to have a main script that calls functions. The script sets up parameters, loads data, calls functions to do the actual work, and generates plots.
%% main_analysis.m
% Main script for analyzing experimental data.
% --- Parameters ---
DATA_FILE = 'experiment_data.mat';
FILTER_CUTOFF = 50; % Hz
PLOT_TIMESERIES = true;
PLOT_SPECTRUM = true;
% --- Load data ---
if ~isfile(DATA_FILE)
error('Data file not found: %s', DATA_FILE);
end
load(DATA_FILE, 'data', 'sample_rate', 'channel_names');
% --- Process data (using functions!) ---
data_filtered = apply_lowpass_filter(data, sample_rate, FILTER_CUTOFF);
[spectra, frequencies] = compute_spectra(data_filtered, sample_rate);
% --- Visualize ---
if PLOT_TIMESERIES
plot_timeseries(data_filtered, sample_rate, channel_names);
end
if PLOT_SPECTRUM
plot_spectra(spectra, frequencies, channel_names);
end
fprintf('Analysis complete.\n');
This pattern gives you the best of both worlds: the script is easy to modify (it’s not buried in a function), and the actual computation is in functions (which are reusable and testable).



