Private functions are useful when you want to limit the scope of a function. Here we will learn how to create private functions and also use them. Private functions are primary functions that are visible only to a limited group of other functions. Generally, we make private functions, if we want to abstract the implementation of a function or in other words limits the scope of the function.
We can make a function private by storing it in a subfolder with the name private, as private functions reside in a subfolder. After storing, the function is now available only to functions immediately above the private subfolder or in other words to the parent folder, in the folder where you stored the function.
Now, create a subfolder with the name private, then create a function in a file named gfg.m, but do not add private to it.
Example:
% MATLAB code for Private function definition function fgf = gfg(a,b,c)
fgf = sqrt(b^2 - 4*a*c); end |
Now, create a function tri.m in the working directory.
% MATLAB code for Private Function function [y1,y2] = tri(a,b,c)
d = fgf(a,b,c); y1 = (-b + d) / (2*a); y2 = (-b - d) / (2*a); end % To run it on the command prompt: % Input the value tri(2,4,-4) |
Output:
>> 0.73205