Skip to content

MATLAB - Local Functions

In MATLAB, all functions must be defined within files. A local function is a function that is defined inside the same file as another function (the main function) or a script. This is a powerful feature for organizing code by keeping helper functions والمساعدة in the same file as the code that uses them, improving readability and maintainability.

Local functions are only visible to the other functions and the script within the same file. This principle is called scope, and it helps prevent naming conflicts and keeps your main workspace clean.

  • Code Organization: Break down a complex algorithm into smaller, more manageable, and logically grouped helper functions without creating many small separate .m files.
  • Encapsulation: Keep helper functions that are not meant for general use private to the file where they are needed. This prevents them from being called accidentally from the command line or other scripts.
  • Readability: Placing a helper function directly below the code that calls it can make the overall logic easier to follow.

To define a local function, simply place its function ... end block within the same .m file as your main function or script, after the main function’s code.

% File name: mainFunction.m
function output = mainFunction(input1, input2)
% This is the main function, visible outside this file.
% It can call the local function.
tempResult = localHelper(input1);
output = tempResult + input2;
end
% --- Local functions are defined below the main function ---
function result = localHelper(input)
% This is a local function. It is ONLY visible to mainFunction.
% It cannot be called from the MATLAB Command Window directly.
result = input * 2;
end

Let’s create a function that computes the mean and standard deviation of a data vector. We’ll use local functions to calculate the sum and sum of squares, demonstrating how to break down the task. Save this as computeStats.m.

% File: computeStats.m
function [avg, stdev] = computeStats(dataVector)
% COMPUTESTATS Calculates the mean and standard deviation of a vector.
% [avg, stdev] = computeStats(dataVector)
% Input validation in the main function
if ~isvector(dataVector) || ~isnumeric(dataVector)
error('Input must be a numeric vector.');
end
n = length(dataVector);
if n < 2
error('Input vector must contain at least two elements.');
end
% Call local functions to perform calculations
total = calculateSum(dataVector);
avg = total / n;
sum_sq_diff = calculateSumOfSquares(dataVector, avg);
stdev = sqrt(sum_sq_diff / (n - 1));
end
% --- Local Helper Functions ---
function s = calculateSum(vec)
% Local function to calculate the sum of vector elements.
s = sum(vec);
end
function ssq = calculateSumOfSquares(vec, mean_val)
% Local function to calculate the sum of squared differences from the mean.
ssq = sum((vec - mean_val).^2);
end

You can now call the main function from the command window, but you cannot call the local functions:

myData = [10, 12, 11.5, 13, 9.5];
[myMean, myStd] = computeStats(myData)
myMean =
11.2000
myStd =
1.3038
calculateSum(myData) % This will produce an error!
Undefined function 'calculateSum' for input arguments of type 'double'.

Understanding scope is crucial:

  • Separate Workspaces: Each function (main and local) has its own private workspace. Variables created in one function are not visible in another by default.
  • Data Passing: Data is passed between functions only through input arguments and output arguments.
  • Parent Workspace Access: Local functions can see and read variables in the workspace of the main function that contains them. However, if a local function modifies a variable with the same name, it creates a local copy. This is different from nested functions, which is a more advanced topic.
  • Task Decomposition: When a function’s algorithm has several distinct, reusable steps.
  • Reducing Clutter: To avoid creating numerous small .m files for helpers that are only used in one place.
  • Script Helpers: You can also place local functions at the end of a script file to support the script’s primary task.