
- MATLAB - Home
- MATLAB - Overview
- MATLAB - Features
- MATLAB - Environment Setup
- MATLAB - Editors
- MATLAB - Online
- MATLAB - Workspace
- MATLAB - Syntax
- MATLAB - Variables
- MATLAB - Commands
- MATLAB - Data Types
- MATLAB - Operators
- MATLAB - Dates and Time
- MATLAB - Numbers
- MATLAB - Random Numbers
- MATLAB - Strings and Characters
- MATLAB - Text Formatting
- MATLAB - Timetables
- MATLAB - M-Files
- MATLAB - Colon Notation
- MATLAB - Data Import
- MATLAB - Data Output
- MATLAB - Normalize Data
- MATLAB - Predefined Variables
- MATLAB - Decision Making
- MATLAB - Decisions
- MATLAB - If End Statement
- MATLAB - If Else Statement
- MATLAB - If…Elseif Else Statement
- MATLAB - Nest If Statememt
- MATLAB - Switch Statement
- MATLAB - Nested Switch
- MATLAB - Loops
- MATLAB - Loops
- MATLAB - For Loop
- MATLAB - While Loop
- MATLAB - Nested Loops
- MATLAB - Break Statement
- MATLAB - Continue Statement
- MATLAB - End Statement
- MATLAB - Arrays
- MATLAB - Arrays
- MATLAB - Vectors
- MATLAB - Transpose Operator
- MATLAB - Array Indexing
- MATLAB - Multi-Dimensional Array
- MATLAB - Compatible Arrays
- MATLAB - Categorical Arrays
- MATLAB - Cell Arrays
- MATLAB - Matrix
- MATLAB - Sparse Matrix
- MATLAB - Tables
- MATLAB - Structures
- MATLAB - Array Multiplication
- MATLAB - Array Division
- MATLAB - Array Functions
- MATLAB - Functions
- MATLAB - Functions
- MATLAB - Function Arguments
- MATLAB - Anonymous Functions
- MATLAB - Nested Functions
- MATLAB - Return Statement
- MATLAB - Void Function
- MATLAB - Local Functions
- MATLAB - Global Variables
- MATLAB - Function Handles
- MATLAB - Filter Function
- MATLAB - Factorial
- MATLAB - Private Functions
- MATLAB - Sub-functions
- MATLAB - Recursive Functions
- MATLAB - Function Precedence Order
- MATLAB - Map Function
- MATLAB - Mean Function
- MATLAB - End Function
- MATLAB - Error Handling
- MATLAB - Error Handling
- MATLAB - Try...Catch statement
- MATLAB - Debugging
- MATLAB - Plotting
- MATLAB - Plotting
- MATLAB - Plot Arrays
- MATLAB - Plot Vectors
- MATLAB - Bar Graph
- MATLAB - Histograms
- MATLAB - Graphics
- MATLAB - 2D Line Plot
- MATLAB - 3D Plots
- MATLAB - Formatting a Plot
- MATLAB - Logarithmic Axes Plots
- MATLAB - Plotting Error Bars
- MATLAB - Plot a 3D Contour
- MATLAB - Polar Plots
- MATLAB - Scatter Plots
- MATLAB - Plot Expression or Function
- MATLAB - Draw Rectangle
- MATLAB - Plot Spectrogram
- MATLAB - Plot Mesh Surface
- MATLAB - Plot Sine Wave
- MATLAB - Interpolation
- MATLAB - Interpolation
- MATLAB - Linear Interpolation
- MATLAB - 2D Array Interpolation
- MATLAB - 3D Array Interpolation
- MATLAB - Polynomials
- MATLAB - Polynomials
- MATLAB - Polynomial Addition
- MATLAB - Polynomial Multiplication
- MATLAB - Polynomial Division
- MATLAB - Derivatives of Polynomials
- MATLAB - Transformation
- MATLAB - Transforms
- MATLAB - Laplace Transform
- MATLAB - Laplacian Filter
- MATLAB - Laplacian of Gaussian Filter
- MATLAB - Inverse Fourier transform
- MATLAB - Fourier Transform
- MATLAB - Fast Fourier Transform
- MATLAB - 2-D Inverse Cosine Transform
- MATLAB - Add Legend to Axes
- MATLAB - Object Oriented
- MATLAB - Object Oriented Programming
- MATLAB - Classes and Object
- MATLAB - Functions Overloading
- MATLAB - Operator Overloading
- MATLAB - User-Defined Classes
- MATLAB - Copy Objects
- MATLAB - Algebra
- MATLAB - Linear Algebra
- MATLAB - Gauss Elimination
- MATLAB - Gauss-Jordan Elimination
- MATLAB - Reduced Row Echelon Form
- MATLAB - Eigenvalues and Eigenvectors
- MATLAB - Integration
- MATLAB - Integration
- MATLAB - Double Integral
- MATLAB - Trapezoidal Rule
- MATLAB - Simpson's Rule
- MATLAB - Miscellenous
- MATLAB - Calculus
- MATLAB - Differential
- MATLAB - Inverse of Matrix
- MATLAB - GNU Octave
- MATLAB - Simulink
MATLAB - Nested Functions
A MATLAB function is a separate, self-contained block of code that performs a specific task and can accept input arguments and return output values. Functions help in organizing your code, making it more readable, and promoting code reuse.
Creating a Simple MATLAB Function
Suppose we want to create a function that calculates the square of a given number. Here's how you can do it −
Step 1: Create a New MATLAB Script
Open MATLAB and create a new script file by clicking on the "New Script" button or using the edit command. Save it with a .m file extension (e.g., square.m).
Step 2: Define the Function
Inside the square.m file, define the function as follows −
function result = square(x) % This function calculates the square of a number. result = x^2; end
In matlab it will be as follows −

In this code −
- function result = square(x) declares the function named square that takes one input argument x and returns a result.
- result = x^2; calculates the square of the input x and assigns it to the variable result.
Step 3: Use the Function
Now that you've created the function, you can use it in your MATLAB workspace or other scripts. Here's how you can use it −
>> num = 5; result = square(num) result = 25 >>
Now that we know how to create normal functions in Matlab, let us get a more detailed understanding of nested functions in matlab.
Nested Functions
Nested functions in MATLAB allow you to define functions within other functions. These nested functions have access to the variables and workspace of their parent functions, which can be very useful for organizing code, encapsulating functionality, and minimizing the use of global variables.
Nested Function Syntax
function outerFunction() % Outer function code function innerFunction() % Nested function code end % Outer function code can call innerFunction end
Important Things to Consider Regarding Nested Functions
- Nested functions can access variables from their parent functions, but the reverse is not true. Parent functions cannot access variables defined in nested functions.
- Nested functions can also access variables from other nested functions within the same parent function.
- Nested functions cannot be called from outside the parent function; they are scoped to the parent function.
- MATLAB allows you to define multiple nested functions within a single parent function.
- Nested functions are a useful way to encapsulate logic and prevent clutter in your MATLAB code.
Example of Simple Nested Function
function area = calculateCircleArea(diameter) % Nested function to calculate radius function radius = calculateRadius(d) radius = d / 2; end % Calculate the area of the circle r = calculateRadius(diameter); area = pi * r^2; end
In this example, calculateRadius is a nested function, and it can access the diameter variable from its parent function calculateCircleArea.
In Matlab you will save and execute above function as shown below −

The execution of the function with values calculateCircleArea() is as follows −
>> d = 10; circleArea = calculateCircleArea(d) circleArea = 78.5398
Returning Nested Function as Output
In MATLAB, you can also return a nested function as the output of the outer function.
function customCalculator = createCalculator(a, b) % Nested function to add two numbers function result = add() result = a + b; end % Nested function to subtract two numbers function result = subtract() result = a - b; end % Return the nested functions as outputs customCalculator.add = @add; customCalculator.subtract = @subtract; end
In this example, the createCalculator function returns a structure with two nested functions, add and subtract, as function handles.
Add Function
The add function calculates the sum of a and b and stores it in the result variable.
Subtract Function
The subtract function calculates the difference between a and b and stores it in the result variable.
After defining these nested functions, the createCalculator function does the following −
Returns a Structure
It creates a structure called customCalculator, which will contain function handles to the add and subtract functions.
Assigns Function Handles
It assigns the function handle @add to the field add of the customCalculator structure.
It assigns the function handle @subtract to the field subtract of the customCalculator structure.
You can use these handles to perform addition and subtraction with the specified values as shown below −
>> calc = createCalculator(5, 3) additionResult = calc.add() subtractionResult = calc.subtract() calc = struct with fields: add: @createCalculator/add subtract: @createCalculator/subtract additionResult = 8 subtractionResult = 2 >>