Nested Functions
Unlike Sub functions, Nested functions are defined inside the primary functions. The scope of a nested function is within the file. One can’t access the nested function from outside the file. Primary function’s workspace can be accessed by all the nested functions that are defined within the body of the primary function.
MATLAB
% A MATLAB program to illustrate nested functions % Primary Function function result = adder(x,y) result = x+y; % Nested Function function print(result) fprintf( 'The sum of two numbers added in the nested function %d' ,result); end % Calling Nested Function print(result); end |
Save the above code with the primary file name adder.m and observe the output by calling the function.
Output:
Functions in MATLAB
Methods are also popularly known as functions. The main aim of the methods is to reuse the code. A method is a block of code which is invoked and executed when it is called by the user. It contains local workspace and independent of base workspace which belongs to command prompt. Let’s take a glance of method syntax.
Syntax:
function [y1, y2 ,y3 . . . . , yn] = functionName(arguments)
. . . . .
end
where, y1 . . . . yn are output variables.
MATLAB syntax is quite peculiar compared to other programming languages. We can return one or more values from a function. We can also pass one or more arguments/variables while calling a function. MATLAB functions must be defined in separate files and function name must match with the file name. Let’s also see the few more ways of defining a function as per the user needs.
- Anonymous Functions
- Sub Functions
- Nested Functions
- Private Functions
Now let’s dive into an example and understand how to define a basic function.
Example:
MATLAB
% A MATLAB program to illustrate % defining a function function result = adder(x, y, z) % This function adds the 3 input arguments result = x+y+z; end |
The comment line that is written just after the function statement works as the help text. Save the above code as adder.m and observe the output by calling it from the command prompt.
Output: