Scripts vs Functions
So far every example has been a script: a list of statements that runs from top to bottom. Once programs grow, you'll want to package reusable pieces as functions. Both live in .m files, but they behave very differently.
Scripts
A script is a .m file with plain statements. Running it is like typing those lines in the Command Window:
- It reads and writes variables in the base workspace (the one you see in the Workspace panel).
- It has no inputs or outputs.
- Variables it creates are still there after it finishes, which is handy for exploration but can cause surprises: a script may accidentally use a leftover variable from earlier.
% File: analyse_temps.m (a script)
temps = [18.5 21.0 23.4 19.8 25.1];
avgTemp = mean(temps);
fprintf('Average: %.2f\n', avgTemp);After >> analyse_temps, the variables temps and avgTemp exist in your workspace.
Functions
A function is a .m file that starts with the keyword function. It has its own private workspace: it sees only its inputs, and only its outputs come back.
% File: average_temp.m (a function file: name matches the function)
function avgTemp = average_temp(temps)
%AVERAGE_TEMP Mean of a vector of temperatures.
avgTemp = mean(temps);
end>> a = average_temp([18.5 21.0 23.4])
a = 20.967The first line declares the output (avgTemp), the function name and the inputs (temps). A function file must be named after its function, so average_temp goes in average_temp.m.
Local functions in scripts
Since MATLAB R2016b a script may also define local functions at the end of the file. They can only be called from inside that file, which is perfect for small helpers. This course uses this form for all runnable examples, so every example stays a single file:
temps = [18.5 21.0 23.4 19.8 25.1];
fprintf('Average: %.2f\n', average_temp(temps));
fprintf('Range: %.2f\n', temp_range(temps));
function a = average_temp(t)
a = mean(t);
end
function r = temp_range(t)
r = max(t) - min(t);
endAverage: 21.56
Range: 6.60
Note: MATLAB requires local functions at the end of a script, each closed with
end. Octave traditionally wants functions defined before they're used and needs a non-function statement (often1;) at the very top of such a file. The examples on this site are written the MATLAB way; the verifier rearranges them for Octave automatically. In your own Octave scripts, put1;first and the functions before the code that calls them, or save each function in its own file.
Private workspaces in action
A function can't see the caller's variables, and the caller can't see the function's internal variables:
rate = 0.2; % lives in the script's workspace
net = after_tax(1000);
fprintf('Net: %g\n', net);
fprintf('rate in the script is still %g\n', rate);
disp(exist('gross')) % 0: the function's variable is gone
function out = after_tax(gross)
rate = 0.3; % a separate variable, private to the function
out = gross * (1 - rate);
endNet: 700
rate in the script is still 0.2
0
The two rate variables are completely independent. That isolation is what makes functions safe to reuse: they can't accidentally change your variables, and their results depend only on their inputs.
Comparing scripts and functions
| Script | Function | |
|---|---|---|
| First line | Any statement | function [outs] = name(ins) |
| Inputs / outputs | None | Any number |
| Workspace | Shared base workspace | Private, created fresh on each call |
| Typical use | A sequence of steps, an analysis, a demo | Reusable calculations |
| File name | Any valid name | Must match the (main) function name |
Organising a project
A typical small project looks like this:
my_project/
main_analysis.m % script: loads data, calls functions, makes plots
clean_data.m % function file
fit_model.m % function file
plot_results.m % function fileMATLAB finds a function file if it's in the current folder or a folder on the search path (addpath('folder')). Since R2016b, a script can also hold its own local helpers, so a small analysis can be a single file.
% A tiny "main script" that uses helpers defined at the end
data = [12 -3 15 0 -7 22];
clean = remove_negatives(data);
report(clean);
function out = remove_negatives(v)
out = v(v >= 0);
end
function report(v)
fprintf('%d values kept, mean %.2f\n', numel(v), mean(v));
end4 values kept, mean 12.25
report has no output at all: functions can be used purely for their effect, like printing.
Test yourself
Which statement about function workspaces is true?
- Functions share variables with the script that calls them
- Each function call has its own private workspace
- Functions can only use global variables
- Function variables persist after the call by default
Where must local functions go in a MATLAB script?
- At the top
- Anywhere
- At the end of the file
- In a separate file only
A function called clean_data should be saved in which file?
clean.mclean_data.mfunctions.m- Any file name