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 −

function calculate

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 −

calculate circle area

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

>>
Advertisements