MATLAB - Private Functions
MATLAB - Private Functions
Section titled “MATLAB - Private Functions”In MATLAB, private functions are a fundamental tool for code organization and encapsulation. They allow you to restrict a function’s visibility, making it accessible only to other functions within the same parent folder. This practice is crucial for building robust, maintainable, and modular applications by hiding implementation details and preventing unintended external use.
What are Private Functions?
Section titled “What are Private Functions?”A private function is a regular MATLAB function (.m file) that you place inside a special subfolder named private. Functions within this private subfolder can only be called by scripts and functions located in the immediate parent directory. They are invisible to the MATLAB path and cannot be called from the command window or from any other location.
This scoping rule helps in:
- Encapsulation: Hiding helper functions that are not meant for public use.
- Name Collision Avoidance: You can have a private function with the same name as a public function (e.g.,
calculate.m) without conflict, as MATLAB gives precedence to the private version when called from the parent directory. - Code Organization: Grouping internal utility functions together, leading to a cleaner project structure.
Creating and Using a Private Function
Section titled “Creating and Using a Private Function”Let’s walk through a practical example. Imagine you are building a simple analysis tool. The main function will perform a calculation, which relies on an internal helper function to format the results. This helper is a perfect candidate for a private function.
First, set up your project folder structure:
myAnalysisProject/├── analyzeData.m % This is our main, public function└── private/ └── formatResult.m % This is our helper, private function- Create the private function
Inside the private subfolder, create a file named formatResult.m with the following content. This function will take a numeric result and a unit string, and format them into a neat text summary.
function formattedStr = formatResult(value, unit)% formatResult Formats a numeric value with its unit into a string.% This is a private function and is not intended for external use.
arguments value (1,1) {mustBeNumeric} unit (1,1) string = "units" end
formattedStr = sprintf("Analysis Result: %.2f %s", value, unit);endNotice the use of the arguments block. This is a modern MATLAB feature for robust function input validation, which is a best practice.
- Create the public function
In the parent directory (myAnalysisProject), create the main function analyzeData.m. This function will call our private formatResult function.
function analyzeData(data)% analyzeData Performs a simple analysis and displays the result.% It uses a private helper function to format the output.
arguments data {mustBeNumeric} end
% Perform some simple calculation meanValue = mean(data, 'all');
% Use the private function to format the output resultString = formatResult(meanValue, "kg");
% Display the final result disp(resultString);end- Run the code
Now, navigate to the myAnalysisProject folder in MATLAB and call the public function from the Command Window:
data = [10.2, 11.5, 9.8, 10.5];analyzeData(data)The output will be:
Analysis Result: 10.50 kgIf you try to call the private function directly from the command window, MATLAB will throw an error because it cannot find the function:
formatResult(10.50, "kg")Unrecognized function or variable 'formatResult'.This demonstrates the enforced encapsulation. You can, however, still view its help documentation using help with the relative path:
help private/formatResult
formatResult Formats a numeric value with its unit into a string. This is a private function and is not intended for external use.Private vs. Public Functions
Section titled “Private vs. Public Functions”Here is a clear breakdown of the differences:
Private Functions
Section titled “Private Functions”- Scope: Limited. Only accessible by functions and scripts in the immediate parent directory.
- Location: Must be placed in a subfolder named
private. - Purpose: Ideal for helper functions, implementation details, and internal utilities that should not be exposed to the end-user of your code.
- Best Practice: Use them to improve code clarity and prevent misuse of internal components. They are a cornerstone of creating robust toolboxes and applications.
Public Functions
Section titled “Public Functions”- Scope: Global. Accessible from anywhere in MATLAB, as long as their containing folder is on the MATLAB path or is the current working directory.
- Location: Can reside in any standard folder (other than
private). - Purpose: Represent the main API or entry points of your application or toolbox. These are the functions you intend for others (or your future self) to use.
- Best Practice: Design public functions with clear, well-documented interfaces and robust error handling, as they form the contract of your software.