Function Definition and File Naming
A MATLAB function file begins with the function keyword: function output = functionName(input1, input2). Critically, when a function lives in its own file, the filename must match the function name exactly (functionName.m), because MATLAB's path resolution looks up functions by filename. Input and output arguments are named in the function signature and are local to that function's workspace.
Cricket analogy: a MATLAB function file computeStrikeRate.m must contain function sr = computeStrikeRate(runs, balls), mirroring how a scorecard entry must match the player it's filed under
Multiple Returns, nargin/nargout, and varargin
MATLAB functions can return several outputs at once by listing them in brackets: [out1, out2] = myFunc(...). Inside a function, nargin tells you how many inputs the caller actually supplied (useful for default arguments via if nargin<2, x=default; end), and nargout tells you how many outputs were requested, letting you skip expensive computation for unrequested outputs. varargin lets a function accept a variable-length, comma-separated list of extra arguments, collected into a cell array.
Cricket analogy: [runs, wickets] = matchSummary(scorecard) returns two outputs at once, and if nargin<2, oversLimit=20; end sets a default T20 over-limit when the caller omits it
function [sr, category] = strikeRateReport(runs, balls, varargin)
if nargin < 2
error('Both runs and balls are required.');
end
sr = (runs / balls) * 100;
if nargout > 1
if sr >= 150
category = 'Explosive';
elseif sr >= 100
category = 'Attacking';
else
category = 'Steady';
end
end
if ~isempty(varargin)
fprintf('Extra context: %s\n', varargin{1});
end
endLocal Functions and Scope
A single .m file can contain multiple functions: the primary function (matching the filename, callable from outside) followed by local functions defined below it. Local functions are visible only to other functions within that same file — they behave like private helpers. Each function, primary or local, has its own workspace: variables created inside don't leak into the caller's workspace or any other function's workspace unless explicitly passed as arguments or returned.
Cricket analogy: a local helper function oversToBalls defined at the bottom of matchStats.m is only visible inside that file, like a team's internal scoring shorthand that outsiders can't reference
Since R2016b, MATLAB allows local functions inside plain script files too, not just function files — you can define helper functions at the end of a .m script as long as function definitions come after all script commands.
Recursion
A MATLAB function can call itself, a technique called recursion, as long as it has a well-defined base case that stops the recursive calls. Each recursive call gets its own independent workspace, so local variables at different recursion depths don't collide. Recursion is elegant for naturally hierarchical or self-similar problems, but deep recursion carries function-call overhead and MATLAB's default recursion limit (500 by default, adjustable) can be hit on very deep problems.
Cricket analogy: a recursive function computing a team's net run rate across a knockout bracket calls itself on each round, with the base case being the final's single match
Recursion without a correctly reachable base case causes infinite recursion, which MATLAB eventually halts with a 'Maximum recursion limit reached' error rather than crashing silently. Always verify the base case is reached for every valid input before relying on recursion in production code.
- The filename of a function .m file must match its primary function's name.
- Functions can return multiple outputs via [out1, out2] = func(...).
- nargin/nargout let a function adapt behavior to how it was called; varargin accepts a variable-length argument list.
- Local functions defined below the primary function in the same file are private to that file.
- Each function call gets an isolated workspace, preventing variable name collisions with the caller.
- Recursion requires a well-defined, reachable base case to avoid hitting MATLAB's recursion limit.
- Since R2016b, script files can also contain local helper functions at the end.
Practice what you learned
1. What must match the primary function's name in a MATLAB function file?
2. What does nargin tell a function?
3. What is varargin used for?
4. Where can a local function in a MATLAB function file be called from?
5. What is required for a recursive MATLAB function to terminate correctly?
Was this page helpful?
You May Also Like
Anonymous Functions and Function Handles
Understand MATLAB's @ syntax for anonymous functions and function handles, closures over workspace variables, and passing handles to arrayfun, cellfun, ode45, and fplot.
Scripts vs Functions
Understand the key differences between MATLAB scripts and functions — workspace behavior, when to use each, and how to convert a script into a reusable function.
Loops in MATLAB
Master for and while loops in MATLAB, including break/continue, nested loops, preallocation, and iterating cell arrays and structs.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics