Private Functions
A typical MATLAB installation contains hundreds of program files, which users can access simply by entering the file name. While this convenient access method is an advantage, it can also lead to clutter and name conflicts, especially due to the existence of some “helper functions” that are used by other functions but are not intended to be called directly by users. Private functions provide an elegant solution to avoid these issues. Any function located in a directory named <span>private</span>
is only visible to functions in the parent directory. Therefore, they can share the same name as functions in other directories. When MATLAB searches for a function, it first looks for local functions, then private functions (relative to the directory of the calling function), then the current directory, and finally the path. Thus, if a private function has the same name as a non-private function (even a built-in function), MATLAB will find the private function first.
<span>gallery</span>
function takes good advantage of private functions, as it is located in the <span>matlab\elmat</span>
directory and provides a collection of matrices. More than 50 matrix generation functions called by <span>gallery</span>
are located in the <span>matlab\elmat\private</span>
directory, and their names can be freely chosen without worrying about conflicts with existing functions (e.g., functions in toolboxes).
The private directory should not be added to the path.
To view the help for the private function <span>fun</span>
, you can use the following command:
help private\fun
Private functions can effectively avoid function name conflicts, making development clearer and more manageable, especially when handling multiple functionalities in large projects.