How to Create a Function in MATLAB: A Complete Guide
MATLAB functions are the backbone of clean, reusable code. Whether you're processing data, running simulations, or automating calculations, knowing how to write a proper function separates scattered scripts from organized, maintainable work. Here's everything you need to understand how MATLAB functions are structured — and what shapes how they behave in practice.
What Is a MATLAB Function?
A function in MATLAB is a block of code that accepts inputs, performs operations, and returns outputs. Unlike a script, which runs in the base workspace and shares variables globally, a function has its own isolated workspace. Variables created inside a function don't bleed into the rest of your environment unless explicitly returned.
This isolation is a feature, not a limitation — it makes functions predictable, testable, and safe to reuse across projects.
The Basic Syntax of a MATLAB Function
Every MATLAB function follows a consistent structure:
function [output1, output2] = functionName(input1, input2) % Function body output1 = input1 + input2; output2 = input1 * input2; end Breaking this down:
function— the required keyword that opens the definition[output1, output2]— the list of values the function returns (use brackets for multiple outputs)functionName— the name you call the function by(input1, input2)— the input arguments passed into the functionend— closes the function block (required in function files with multiple functions)
A function with a single output doesn't need brackets:
function result = squareValue(x) result = x .^ 2; end 🗂️ Where to Write Your Function: Three Approaches
How you store and call a MATLAB function depends on your workflow and project size.
1. Function File (Recommended for Reuse)
Save the function in a .m file where the filename matches the function name exactly. A function named squareValue must live in squareValue.m. MATLAB uses the filename to locate and call it.
This is the standard approach for any function you'll use more than once or share across projects.
2. Local Function Within a Script
Since MATLAB R2016b, you can define functions at the bottom of a script file after all script-level code:
% Script section x = 5; result = doubleIt(x); disp(result) % Local function function y = doubleIt(n) y = n * 2; end Local functions are only accessible within that file — they won't appear in your general workspace.
3. Anonymous Function
For short, single-expression operations, anonymous functions offer a compact alternative:
square = @(x) x.^2; result = square(4); % Returns 16 Anonymous functions are defined inline, stored as variables, and passed around like values. They're ideal for callbacks, quick transformations, or passing operations into functions like arrayfun or cellfun.
Handling Inputs and Outputs Flexibly
Optional Inputs with nargin
MATLAB provides nargin (number of input arguments) and nargout (number of output arguments) to write functions that adapt to how they're called:
function result = addNumbers(a, b) if nargin < 2 b = 10; % Default value end result = a + b; end Multiple Outputs
Callers can request one or all outputs — MATLAB only computes what's asked for when used efficiently:
[sumResult, productResult] = myFunction(3, 4); If only one output is needed, the caller simply omits the rest.
Key Rules That Affect How Your Function Behaves
| Rule | Detail |
|---|---|
| File naming | Filename must match function name for function files |
| Workspace isolation | Function variables are private by default |
| First function in file | Must match the filename; secondary functions are local |
end keyword | Required when multiple functions exist in one file |
nargin/nargout | Enable flexible, optional argument handling |
| Recursion | Supported — a function can call itself |
⚙️ Vectorization and the Dot Operator
A common source of errors for new MATLAB users: operations inside functions often need to handle arrays, not just scalars. Use the dot operator (.) for element-wise arithmetic:
x .* ymultiplies element by elementx .^ 2squares each element individuallyx * yperforms matrix multiplication — likely not what you want on plain numeric arrays
Designing your function to handle vectors from the start makes it far more flexible when called with real dataset inputs.
When to Use Scripts vs. Functions
Scripts are convenient for exploratory work — running top-to-bottom, no input/output structure required. Functions are the right choice when:
- The same logic needs to run with different inputs
- You want to avoid variable name conflicts across your workspace
- You're building something others will call or modify
- You need to test logic independently of the rest of your code
What Shapes Your Specific Implementation 🧩
The "right" way to structure a function depends on factors specific to your situation:
- Project scale — a one-off analysis calls for different organization than a packaged toolbox
- MATLAB version — local functions in scripts,
argumentsblocks for input validation, andmustBe*validators were introduced at different release points - Performance needs — vectorized operations, persistent variables, and
mexfiles matter differently depending on data volume - Collaboration — shared functions need consistent naming conventions, clear documentation headers, and input validation that single-user scripts can skip
- Toolbox dependencies — some input/output patterns are standard in Signal Processing or Statistics toolboxes but unnecessary for basic math work
The mechanics of writing a MATLAB function are consistent. What varies is how much structure, flexibility, and error-handling your particular project actually warrants — and that depends entirely on what you're building and who's going to use it.