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
% 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
% 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:
- In the nested function, you can use those variables too which were not necessarily passed as input arguments from the user.
- From the parent function, you can control the working of the nested function i.e., you can handle the data necessary to run the nested function.
Characteristics of Nested functions:
You can also share variables from the nested function to the main function.
Example 3:
Matlab
% 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
% 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( 'w3wiki' ); end end |
Output:
You can share variables among two nested functions, under the same parent function.
Example 5:
Matlab
% 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
% 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: