Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 45 ยท Programming

Scripts and Functions

Learn how MATLAB and Octave scripts differ from function files, return multiple outputs, use nargin and nargout, set defaults and keep variables in scope.

Typing commands one by one is fine for exploring, but sooner or later you want to save your work and reuse it. MATLAB and Octave give you two ways to do that. A script is a file of commands that runs in your current workspace, exactly as if you had typed them. A function is a file with its own private workspace that takes inputs and returns outputs, like a mathematical function.

Knowing which to use, and how the two behave differently, will keep your programs organized and prevent surprising bugs such as one piece of code silently overwriting another's variables.

This lesson is read-only. Function files must be saved on disk to run, which cannot be done in a browser editor here, so the code blocks marked matlab show real MATLAB and Octave code, and the Python TryIts mirror the ideas with ordinary Python functions.

Script or function?

Script Runs in your workspace. No inputs or outputs.
Function Own workspace. Inputs in, outputs out.

Reach for functions as soon as you reuse code.

1 / 2

Scripts

A script is a plain text file with the extension .m. Running it, by typing its name (without .m) or pressing Run in the editor, executes its lines in order in the base workspace. Variables the script creates stay in your workspace, and variables you already had are visible to it.

MATLAB
% file: setup_data.m
x = linspace(0, 2*pi, 100);
y = sin(x);
peak = max(y);

After you run setup_data, the variables x, y and peak appear in the workspace. That is convenient for a small analysis, and dangerous for larger programs: a script can overwrite a variable you were using, and it is hard to reuse with different data because it has no inputs.

Function files

A function file starts with the keyword function, names its outputs, name and inputs, and ends the body with end (required when the file contains several functions or nested ones, and a good habit everywhere):

MATLAB
% file: circle_area.m
function a = circle_area(r)
    a = pi * r.^2;
end

Save it as circle_area.m. Then call it from the command window or any other code:

MATLAB
circle_area(3)           % 28.2743
circle_area([1 2 3])     % 3.1416  12.5664  28.2743

Because the body uses .^ (see Arithmetic: Matrix vs Element-wise), the function works on scalars and arrays alike.

The file name decides the function name. If the file is circle_area.m but the first line says function a = area_of_circle(r), MATLAB uses circle_area and ignores the other name. Keep the two the same. The file also has to be in the current folder or on the search path, which you can check with which circle_area.

Multiple outputs

List several outputs in square brackets. The caller picks how many to collect:

MATLAB
function [lo, hi, avg] = describe(v)
    lo  = min(v);
    hi  = max(v);
    avg = mean(v);
end
MATLAB
[a, b, c] = describe([4 9 1 7]);   % a=1, b=9, c=5.25
[a, b]    = describe([4 9 1 7]);   % c is simply not returned
low       = describe([4 9 1 7]);   % only the first output
[~, top]  = describe([4 9 1 7]);   % ~ ignores an output

An output is only returned if the function actually assigned it. If you forget to set hi inside the function and ask for it, you get an error saying the output was not assigned.

Python Multiple return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python returns one tuple and the caller unpacks it, while MATLAB really has several outputs, and the function can find out how many were requested (next section).

nargin and nargout

Inside a function, nargin is the number of inputs the caller supplied and nargout is the number of outputs they asked for. They let one function behave sensibly with fewer arguments, the usual way to build default arguments:

MATLAB
function y = power_of(x, p)
    if nargin < 2
        p = 2;              % default exponent
    end
    y = x .^ p;
end
MATLAB
power_of(5)        % 25
power_of(5, 3)     % 125

Other idioms you will see in real code:

MATLAB
if nargin < 2 || isempty(p)     % treat [] as "use the default"
    p = 2;
end
if nargout > 1
    extra = expensive_calculation(x);   % skip work nobody asked for
end

For a variable number of inputs, use varargin, a cell array of all remaining arguments (see Cell Arrays); varargout does the same for outputs. Newer MATLAB also has an arguments block that declares types and defaults at the top of a function. It does not exist in Octave, so use nargin checks for portable code. Octave offers print_usage() to report a wrongly called function.

Python Defaults and variable arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python's default values and *args do the work of nargin checks and varargin directly. The MATLAB versions are more manual, but they let a single file accept many call styles.

Local and nested functions

One file can hold more than one function. The first one is the main function, callable from outside. The rest are local functions (also called subfunctions) and are visible only inside that file:

MATLAB
% file: normalize_scores.m
function out = normalize_scores(v)
    out = (v - mean_of(v)) / spread_of(v);
end

function m = mean_of(v)
    m = sum(v) / numel(v);
end

function s = spread_of(v)
    s = max(v) - min(v);
end

Local functions are perfect for splitting a task into clear steps without cluttering the folder with tiny files. A local function takes priority over a file of the same name elsewhere.

A nested function is defined inside another function, before that function's end. It can read and change the outer function's variables, which makes it handy for callbacks, but it also makes code harder to follow. When using them, close every function in the file with end.

Scripts can contain local functions too, but the rules differ. MATLAB requires them at the end of the script file. Octave requires them to be defined before they are used, and the file must not begin with a function definition, or Octave treats it as a function file. A common trick is to start such an Octave script with a harmless line 1;. Since Octave also lets you type function definitions straight into the command window (command-line functions), you can experiment without saving files, which MATLAB does not allow.

Variable scope

Each function has its own workspace. A variable created inside a function exists only while the function runs, and the caller never sees it unless it is returned. Variables the caller has are invisible inside the function unless passed in:

MATLAB
function r = scale(v)
    factor = 10;          % exists only inside scale
    r = v * factor;
end
MATLAB
y = scale([1 2 3]);       % y = [10 20 30]
factor                    % error: 'factor' undefined

This isolation is the main reason to prefer functions. You can reuse a name like i or temp inside a function without damaging your work. MATLAB also offers global variables shared by name across workspaces, but they make programs hard to test, so pass values as arguments instead.

Arguments are passed by value in effect: if the function modifies its input, the caller's copy stays unchanged. MATLAB copies lazily, only when you actually change something, so passing a big matrix to a function that merely reads it costs nothing extra.

Do not name a variable or function after a built-in such as sum, max or plot. The new name shadows the real one and the built-in stops working until you clear it. Check a name first with which name or exist('name').

Documenting a function

The first block of comment lines after the function line becomes the help text. It is what help circle_area prints, so write one line that says what the function does, then notes on inputs and outputs. Good help text pays back quickly, because the function you wrote last month will look like someone else's code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A function file is saved as speed.m, but its first line reads function v = velocity(d, t). What name do you call it with?

    The file name decides the name of the function when it is called from outside. Keep the file name and function name identical to avoid confusion.
  2. 2. What does nargin hold inside a function?

    nargin counts the input arguments passed in the call. nargout counts the outputs the caller asked for.
  3. 3. What is the main difference between a script and a function?

    Script variables live in the base workspace, so scripts can overwrite your variables. A function's variables are private unless returned.
  4. 4. Which statement about local functions in a function file is true?

    Local functions follow the main function in the same file and can be called only by code in that file.
  5. 5. How does a function skip the work of an extra output nobody asked for?

    nargout tells the function how many outputs the caller requested, so it can skip expensive calculations when they are not needed.

Summary

  • A script runs in your workspace; a function file has its own workspace, inputs and outputs.
  • The function file name decides the callable name; keep both the same and keep the file on the path.
  • Return several values with [a, b] = f(...), and use nargin and nargout for default arguments and optional work.
  • Local functions (after the main function) are private to their file; nested functions share the outer variables.
  • Octave differs: script-file functions must be defined before use, the file must not start with function, and command-line functions are allowed.

Next: Anonymous Functions and Function Handles, for tiny functions you define in one line.