0
0
MATLABdata~5 mins

Local functions in MATLAB

Choose your learning style9 modes available
Introduction

Local functions help you organize your code by keeping small helper functions inside a main file. This keeps related code together and easy to manage.

When you want to break a big task into smaller steps inside one file.
When you want to reuse a small piece of code only within one main function.
When you want to keep your main script or function clean and readable.
When you want to avoid cluttering the workspace with many separate function files.
Syntax
MATLAB
function mainFunction()
    % main code here
end

function output = localFunction(input)
    % helper code here
end

Local functions are placed after the main function or script in the same file.

They can only be called from within the main function or other local functions in the same file.

Examples
This example shows a main function greet that calls a local function sayHello to create a greeting message.
MATLAB
function greet()
    message = sayHello('Alice');
    disp(message);
end

function msg = sayHello(name)
    msg = ['Hello, ' name '!'];
end
This example uses two local functions add and square inside the main function addAndSquare to perform calculations step-by-step.
MATLAB
function result = addAndSquare(a, b)
    sumVal = add(a, b);
    result = square(sumVal);
end

function s = add(x, y)
    s = x + y;
end

function sq = square(n)
    sq = n^2;
end
Sample Program

This program defines a main function main that uses a local function multiplyAndAdd. This local function calls two other local functions multiply and addFive to calculate the final result.

MATLAB
function main()
    x = 5;
    y = 3;
    result = multiplyAndAdd(x, y);
    fprintf('Result is %d\n', result);
end

function output = multiplyAndAdd(a, b)
    product = multiply(a, b);
    output = addFive(product);
end

function p = multiply(x, y)
    p = x * y;
end

function r = addFive(num)
    r = num + 5;
end
OutputSuccess
Important Notes

Local functions cannot be called from outside their file.

They help keep your code organized and avoid creating many separate files.

Summary

Local functions live inside the same file as the main function or script.

They help break down tasks into smaller, reusable pieces.

They keep your workspace clean by not creating extra function files.