Open In App

Nested Functions in MATLAB

Functions in any programming language are some blocks of code, which could be reused whenever required, by just calling the name. It reduces so much of human effort and also rewriting of the same code, and makes the entire code big. 

Declaring a Function:

 To declare a function in MATLAB we use given below:



Syntax:

function [x1,x2,...,xn] = myfunc(k1,k2,...,km)

Let’s understand the syntax first. Here, myfunc is the name of the function. The x1,x2,…,xn are the parameter that is sent to the function, and k1,k2,…,kn are the output obtained. 
 



Example 1:




% MATLAB function of adding two numbers 
function x = multiply(a,b)
    x= a*b;
end

Output:

Nested Function:

When you declare one function, under another parent function then it is known as a nested function.

Example 2:




% MATLAB function for Nested function
function parentfunc
disp('I am a parent function')
nestedfunc
    function nestedfunc
        disp('I am a nested function')
    end
end

Output:

Advantages:

Characteristics of Nested functions:

You can also share variables from the nested function to the main function.

Example 3:




% MATLAB Code for share variables from the
% nested function to the main function
function parent
    nestedfunc
    function nestedfunc
        x = 5;
    end
      x = x+1;
    disp(x);
end

Output:

You can nest more than one function under the same parent function. 

Example 4:




% MATLAB Code for more than one function
% under the same parent function
function parent
    nestedfunc1
    nestedfunc2
    function nestedfunc1
        fprintf('GFG\n');
    end
    function nestedfunc2 
        fprintf('GeeksforGeeks');
    end
end

Output:

You can share variables among two nested functions, under the same parent function.

Example 5:




% MATLAB code for two nested functions,
% under the same parent function
function parent 
    x = 5
    nested1
    nested2
    function nested1
        x = x*2;
    end
    function nested2
        x = x+5;
    end
disp(x)
end

 Output:

You can also handle nested functions with the help of the parent function using a variable in the parent function.

Example 6: 




% MATLAB Code for handle nested functions with 
% the help of the parent function  
function parentfun
x = 5;
a = nestedfunc;
  
       function b = nestedfunc
        b = x + 1;
        fprintf('GFG\n');
       end 
    disp(a);
end

Output:


Article Tags :