Skip to content

MATLAB - Sub-functions

MATLAB - Code Modularity with Local Functions

Section titled “MATLAB - Code Modularity with Local Functions”

Local functions (also commonly known as sub-functions) are a powerful feature in MATLAB for improving code organization and readability. They allow you to define multiple functions within a single .m file. The primary function in the file is the main function, and any functions defined after it are local functions. This approach is ideal for creating helper routines that are only relevant to the main function, encapsulating logic and reducing clutter in your project’s main folder.

To create a file with local functions, simply define your main function first, followed by the function keyword for each local function. The end statement for the main function must come before the definitions of any local functions.

Let’s create a main function analyzeData that uses a local function calculateStats to compute the mean and standard deviation. Save this code in a file named analyzeData.m.

% --- Main Function ---
function [dataMean, dataStd] = analyzeData(inputVector)
% This is the main function. It takes a vector and returns its statistics.
% Call the local function to perform the calculation
[dataMean, dataStd] = calculateStats(inputVector);
% Display the results
fprintf('Mean: %.2f, Standard Deviation: %.2f\n', dataMean, dataStd);
end % End of the main function
% --- Local Function ---
function [meanVal, stdVal] = calculateStats(data)
% This is a local function, visible only within this file.
% It calculates the mean and standard deviation of the input data.
if ~isvector(data) || ~isnumeric(data)
error('Input must be a numeric vector.');
end
meanVal = mean(data);
stdVal = std(data);
end % End of the local function

To execute this, call the main function from the MATLAB Command Window:

myData = [12, 15, 11, 18, 14, 22];
[m, s] = analyzeData(myData);
Mean: 15.33, Standard Deviation: 4.08
m =
15.3333
s =
4.0825

You can call analyzeData from anywhere, but you cannot call calculateStats directly from the Command Window, as its scope is limited to the analyzeData.m file.

Scope: Local Functions vs. Nested Functions

Section titled “Scope: Local Functions vs. Nested Functions”

MATLAB provides two ways to define functions within another: local functions and nested functions. They serve similar purposes but have a crucial difference in their variable scope.

FeatureLocal FunctionsNested Functions
DefinitionDefined within a file, after the main function. Each has its own function ... end block.Defined inside another function, before the parent function’s end statement.
Variable ScopeHas its own separate workspace. Cannot directly access variables from the main function. Data must be passed explicitly via arguments.Shares the workspace of the parent function. Can directly access and modify variables from its parent without them being passed as arguments.
Use CaseGeneral-purpose helper functions. Promotes clean separation of concerns and code reuse within a single file.Tightly-coupled helper functions that need to share state with the parent, such as in optimization routines or creating function handles with persistent state.
function mainFunction
myValue = 10;
% Define the nested function
function nestedHelper
% This function can see and use 'myValue' from its parent
disp(['The value from the parent is: ', num2str(myValue)]);
end
% Call the nested function
nestedHelper();
myValue = 20; % Modify the parent's variable
nestedHelper(); % Call it again to see the change
end
  • Modularity: Break down complex problems into smaller, manageable pieces without creating many separate .m files.
  • Readability: A well-named local function makes the main function’s code easier to follow, as complex implementation details are hidden away.
  • Encapsulation: Prevents helper functions from being called accidentally from other parts of a larger project, avoiding naming conflicts and unintended side effects.
  • Code Organization: Keeps related functionality grouped together in a single, self-contained file.
  • When to Avoid: If a helper function is useful for multiple, unrelated main functions, it should not be a local function. Instead, place it in its own .m file and add its folder to the MATLAB path.