MATLAB - Functions Overloading
MATLAB - Function Overloading and Overriding
Section titled “MATLAB - Function Overloading and Overriding”In MATLAB, the concept of having multiple functions with the same name is handled in two primary ways: function overloading by varying the number of input arguments, and method overriding in object-oriented programming. This allows you to create flexible and intuitive interfaces, where a single function name can adapt its behavior based on the context in which it’s called.
Why Use Overloading and Overriding?
Section titled “Why Use Overloading and Overriding?”These techniques are fundamental to writing clean, reusable, and professional MATLAB code. They allow you to:
- Create Flexible Functions: Design a single function that can perform different operations based on the number or type of inputs, reducing the need for many similarly named functions (e.g.,
addTwoNumbers,addThreeNumbers). - Specialize Behavior for Custom Classes: Make objects of your custom class behave like MATLAB’s built-in types. For example, you can define how a
plotordispfunction should work specifically for your object. - Extend Existing Functionality: In object-oriented programming, a subclass can provide a specialized version of a method inherited from its parent class (overriding), tailoring its behavior without altering the parent class.
Implementing Overloading and Overriding
Section titled “Implementing Overloading and Overriding”MATLAB’s approach depends on whether you are writing a procedural script or defining a class.
1. Overloading with Variable Arguments (nargin)
Section titled “1. Overloading with Variable Arguments (nargin)”For standard functions (not in a class), you can simulate overloading by checking the number of input arguments provided by the user with the nargin keyword. This allows a single function to exhibit different behaviors.
2. Method Overriding in Object-Oriented Programming (OOP)
Section titled “2. Method Overriding in Object-Oriented Programming (OOP)”In OOP, when you create a class, you can define methods with the same names as existing MATLAB functions (e.g., plot, disp) or methods from a superclass. When you call that function with an object of your class, MATLAB’s dispatch mechanism invokes your class-specific method. This is known as overriding.
- Dominant Argument Rule: When a function is called with arguments of different classes, MATLAB determines which method to call based on the class hierarchy. User-defined classes have precedence over built-in types.
- Implementation: To override a function, simply define a method with the same name within your
classdeffile. This method must accept an object of your class as an argument.
Code Examples
Section titled “Code Examples”Example 1: Function Overloading by Number of Inputs
Section titled “Example 1: Function Overloading by Number of Inputs”Instead of creating multiple add methods, a more modern and robust approach is to use nargin or varargin to handle a variable number of inputs in a single method. Here’s a function that calculates the area of a rectangle or a square.
function area = calculateArea(width, height) % Calculates the area of a shape. % If one input is provided, it's treated as a square. % If two inputs are provided, it's treated as a rectangle.
narginchk(1, 2); % Ensure 1 or 2 inputs are given
if nargin == 1 % Square: area = side^2 area = width^2; fprintf('Calculating area of a square with side %.2f\n', width); else % Rectangle: area = width * height area = width * height; fprintf('Calculating area of a rectangle with width %.2f and height %.2f\n', width, height); endend
% --- How to use it ---area1 = calculateArea(5); % Called with one argumentdisp(['Area 1: ', num2str(area1)]);
area2 = calculateArea(5, 10); % Called with two argumentsdisp(['Area 2: ', num2str(area2)]);When you run this code, MATLAB’s nargin check directs the flow to the correct calculation, effectively overloading the calculateArea function’s behavior.
Example 2: Overriding the disp Function for a Custom Class
Section titled “Example 2: Overriding the disp Function for a Custom Class”Let’s create a Patient class and override the built-in disp function to provide a custom, more informative display when a Patient object is printed to the console.
classdef Patient properties Name string ID double Data double end
methods function obj = Patient(name, id, data) if nargin > 0 obj.Name = name; obj.ID = id; obj.Data = data; end end
% Override the built-in disp() function function disp(obj) fprintf('--- Patient Record ---\n'); fprintf(' Name: %s\n', obj.Name); fprintf(' ID: %d\n', obj.ID); fprintf(' Data Points: %d\n', numel(obj.Data)); fprintf(' Mean Value: %.2f\n', mean(obj.Data)); fprintf('----------------------\n'); end endend
% --- How to use it ---% Create an instance of the Patient classp = Patient("John Doe", 123, [98.6, 99.1, 98.4, 98.7]);
% Now, just typing the variable name in the command window will call our custom disp methoddisp(p);Without the overridden disp method, MATLAB would show a generic object property list. With it, we get a clean, formatted summary tailored to our class.
Example 3: Method Overriding with Inheritance
Section titled “Example 3: Method Overriding with Inheritance”Method overriding is central to inheritance. A subclass can provide its own version of a method from its superclass. Here, Circle and Rectangle both inherit from Shape but provide their own specific calculateArea method.
% --- Base Class: Shape.m ---classdef Shape methods function a = calculateArea(obj) disp('Area calculation not defined for a generic shape.'); a = NaN; % Not a Number end endend
% --- Subclass: Circle.m ---classdef Circle < Shape properties Radius end methods function obj = Circle(r) obj.Radius = r; end % Override calculateArea for Circle function a = calculateArea(obj) a = pi * obj.Radius^2; end endend
% --- Subclass: Rectangle.m ---classdef Rectangle < Shape properties Width Height end methods function obj = Rectangle(w, h) obj.Width = w; obj.Height = h; end % Override calculateArea for Rectangle function a = calculateArea(obj) a = obj.Width * obj.Height; end endend
% --- How to use it ---shape = Shape();circle = Circle(10);rectangle = Rectangle(5, 8);
area1 = shape.calculateArea(); % Calls Shape's methodarea2 = circle.calculateArea(); % Calls Circle's methodarea3 = rectangle.calculateArea(); % Calls Rectangle's method
fprintf('Generic Shape Area: %.2f\n', area1);disp(['Circle Area: ', num2str(area2)]);disp(['Rectangle Area: ', num2str(area3)]);