TExcelTAD
Home › MATLAB / Octave › Scripts vs Functions

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.
matlab
% 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.

matlab
% 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
text
>> a = average_temp([18.5 21.0 23.4])
a = 20.967

The 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:

matlab · try it yourself
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);
end
Average: 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 (often 1;) 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, put 1; 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:

matlab · try it yourself
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);
end
Net: 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:

text
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 file

MATLAB 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.

matlab · try it yourself
% 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));
end
4 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?

  1. Functions share variables with the script that calls them
  2. Each function call has its own private workspace
  3. Functions can only use global variables
  4. Function variables persist after the call by default

Where must local functions go in a MATLAB script?

  1. At the top
  2. Anywhere
  3. At the end of the file
  4. In a separate file only

A function called clean_data should be saved in which file?

  1. clean.m
  2. clean_data.m
  3. functions.m
  4. Any file name