
- MATLAB - Home
- MATLAB - Overview
- MATLAB - Features
- MATLAB - Environment Setup
- MATLAB - Editors
- MATLAB - Online
- MATLAB - Workspace
- MATLAB - Syntax
- MATLAB - Variables
- MATLAB - Commands
- MATLAB - Data Types
- MATLAB - Operators
- MATLAB - Dates and Time
- MATLAB - Numbers
- MATLAB - Random Numbers
- MATLAB - Strings and Characters
- MATLAB - Text Formatting
- MATLAB - Timetables
- MATLAB - M-Files
- MATLAB - Colon Notation
- MATLAB - Data Import
- MATLAB - Data Output
- MATLAB - Normalize Data
- MATLAB - Predefined Variables
- MATLAB - Decision Making
- MATLAB - Decisions
- MATLAB - If End Statement
- MATLAB - If Else Statement
- MATLAB - If…Elseif Else Statement
- MATLAB - Nest If Statememt
- MATLAB - Switch Statement
- MATLAB - Nested Switch
- MATLAB - Loops
- MATLAB - Loops
- MATLAB - For Loop
- MATLAB - While Loop
- MATLAB - Nested Loops
- MATLAB - Break Statement
- MATLAB - Continue Statement
- MATLAB - End Statement
- MATLAB - Arrays
- MATLAB - Arrays
- MATLAB - Vectors
- MATLAB - Transpose Operator
- MATLAB - Array Indexing
- MATLAB - Multi-Dimensional Array
- MATLAB - Compatible Arrays
- MATLAB - Categorical Arrays
- MATLAB - Cell Arrays
- MATLAB - Matrix
- MATLAB - Sparse Matrix
- MATLAB - Tables
- MATLAB - Structures
- MATLAB - Array Multiplication
- MATLAB - Array Division
- MATLAB - Array Functions
- MATLAB - Functions
- MATLAB - Functions
- MATLAB - Function Arguments
- MATLAB - Anonymous Functions
- MATLAB - Nested Functions
- MATLAB - Return Statement
- MATLAB - Void Function
- MATLAB - Local Functions
- MATLAB - Global Variables
- MATLAB - Function Handles
- MATLAB - Filter Function
- MATLAB - Factorial
- MATLAB - Private Functions
- MATLAB - Sub-functions
- MATLAB - Recursive Functions
- MATLAB - Function Precedence Order
- MATLAB - Map Function
- MATLAB - Mean Function
- MATLAB - End Function
- MATLAB - Error Handling
- MATLAB - Error Handling
- MATLAB - Try...Catch statement
- MATLAB - Debugging
- MATLAB - Plotting
- MATLAB - Plotting
- MATLAB - Plot Arrays
- MATLAB - Plot Vectors
- MATLAB - Bar Graph
- MATLAB - Histograms
- MATLAB - Graphics
- MATLAB - 2D Line Plot
- MATLAB - 3D Plots
- MATLAB - Formatting a Plot
- MATLAB - Logarithmic Axes Plots
- MATLAB - Plotting Error Bars
- MATLAB - Plot a 3D Contour
- MATLAB - Polar Plots
- MATLAB - Scatter Plots
- MATLAB - Plot Expression or Function
- MATLAB - Draw Rectangle
- MATLAB - Plot Spectrogram
- MATLAB - Plot Mesh Surface
- MATLAB - Plot Sine Wave
- MATLAB - Interpolation
- MATLAB - Interpolation
- MATLAB - Linear Interpolation
- MATLAB - 2D Array Interpolation
- MATLAB - 3D Array Interpolation
- MATLAB - Polynomials
- MATLAB - Polynomials
- MATLAB - Polynomial Addition
- MATLAB - Polynomial Multiplication
- MATLAB - Polynomial Division
- MATLAB - Derivatives of Polynomials
- MATLAB - Transformation
- MATLAB - Transforms
- MATLAB - Laplace Transform
- MATLAB - Laplacian Filter
- MATLAB - Laplacian of Gaussian Filter
- MATLAB - Inverse Fourier transform
- MATLAB - Fourier Transform
- MATLAB - Fast Fourier Transform
- MATLAB - 2-D Inverse Cosine Transform
- MATLAB - Add Legend to Axes
- MATLAB - Object Oriented
- MATLAB - Object Oriented Programming
- MATLAB - Classes and Object
- MATLAB - Functions Overloading
- MATLAB - Operator Overloading
- MATLAB - User-Defined Classes
- MATLAB - Copy Objects
- MATLAB - Algebra
- MATLAB - Linear Algebra
- MATLAB - Gauss Elimination
- MATLAB - Gauss-Jordan Elimination
- MATLAB - Reduced Row Echelon Form
- MATLAB - Eigenvalues and Eigenvectors
- MATLAB - Integration
- MATLAB - Integration
- MATLAB - Double Integral
- MATLAB - Trapezoidal Rule
- MATLAB - Simpson's Rule
- MATLAB - Miscellenous
- MATLAB - Calculus
- MATLAB - Differential
- MATLAB - Inverse of Matrix
- MATLAB - GNU Octave
- MATLAB - Simulink
MATLAB - Operator Overloading
Operator overloading in MATLAB allows you to define custom behaviors for standard operators (like +, -, *, /, etc.) when they are used with objects of your custom class. This is particularly useful when you want objects of your class to interact with each other or with other MATLAB types in a natural and intuitive way, similar to how built-in types behave.
Why Overload Operators?
Overloading operators in MATLAB allows you to define custom behaviors for standard operators (like +, *, -, etc.) when used with objects of your class. This makes it possible to use your objects in a way that feels natural and integrates seamlessly with MATLAB's built-in functionality.
For example −
- Arithmetic Operations − If your class contains numeric data, you can define how operators like + or * should work with your objects. This way, you can perform arithmetic operations directly on your objects.
- Relational Operations − By defining relational operators (like <, >, ==), you can use your objects in conditional statements such as if or switch.
In a simple way overloading operators makes your custom objects behave like built-in MATLAB types, allowing you to use them more intuitively in your code.
How to Define Operators?
In MATLAB, you can customize how standard operators (like +, -, *, etc.) work with objects of your class by defining methods that handle these operations. Each operator has a corresponding method name (for example, the + operator corresponds to the plus method). To implement an operator, you create a method in your class with the appropriate name and define the steps for the operation.
Object Precedence in Operations
User-defined classes have higher precedence than built-in classes. This means if you define an object of your class and use it with a built-in class object (like a double), MATLAB will use your class's method if it exists. For instance, if p is an object of your class and q is a double, both p + q and q + p will call your class's plus method. When objects from different user-defined classes are used together, MATLAB follows precedence rules to decide which method to call.
Operator Precedence
MATLAB evaluates expressions based on a predefined order of operations, known as precedence levels. This determines which parts of an expression are calculated first. Operators within the same level are evaluated from left to right. Here is the order from highest to lowest precedence:
- Parentheses: ()
- Transpose and Power: .', .^, .', ^
- Unary Operations: Unary minus, plus, and logical negation with power: .^-, .^+, .^~
- Unary Operations: Unary plus, minus, logical negation: +, -, ~
- Multiplication and Division: .*, ./, .\, *, /, \
- Addition and Subtraction: +, -
- Colon Operator: :
- Relational Operators: <, <=, >, >=, ==, ~=
- Element-wise AND: &
- Element-wise OR: |
- Short-circuit AND: &&
- Short-circuit OR: ||
Precedence of AND and OR Operators
MATLAB gives the & operator higher precedence than the | operator. For example, the expression a | b & c is evaluated as a | (b & c). To avoid confusion, it's best to use parentheses to clearly indicate the intended order of operations.
Overriding Default Precedence
You can change the default order of evaluation by using parentheses. For example:
A = [3 9 5]; B = [2 1 5]; C = A./B.^2 % Evaluates division after exponentiation % C = [0.7500 9.0000 0.2000] C = (A./B).^2 % Evaluates division before exponentiation % C = [2.2500 81.0000 1.0000]
Output will be −
In short, defining operators and understanding their precedence allows you to control how your custom objects interact with MATLAB's built-in functions and ensures that expressions are evaluated in the order you intend.
Examples of Operator Overloading
Operator overloading in MATLAB allows you to define how specific operators behave when used with objects of your class. Below are a few examples with explanations to illustrate this concept.
Example 1: Overloading the Plus Operator
Let's create a simple class to represent a 2D point and overload the + operator to add two points together.
classdef Point properties X Y end methods function obj = Point(x, y) if nargin > 0 obj.X = x; obj.Y = y; end end % Overload the plus operator function result = plus(obj1, obj2) result = Point(obj1.X + obj2.X, obj1.Y + obj2.Y); end end end
Save above code as Point.m
In this example,
- we define a Point class with properties X and Y.
- Function Definition: function obj = Point(x, y) defines a constructor method for the Point class. The constructor is a special method that is called when a new instance of the class is created.
- The constructor takes two inputs, x and y, which are used to initialize the properties X and Y.
- The if nargin > 0 condition checks if the constructor was called with any arguments. nargin is a built-in variable that returns the number of input arguments passed to the function. If no arguments are passed (i.e., nargin == 0), the properties X and Y are not modified.
- obj.X = x; and obj.Y = y; assign the values of x and y to the properties X and Y of the new Point object (obj).
- Function result = plus(obj1, obj2) defines a method to overload the + operator for Point objects. This means that when you use the + operator with two Point objects, this method will be called.The method takes two inputs, obj1 and obj2, which are instances of the Point class.
- result = Point(obj1.X + obj2.X, obj1.Y + obj2.Y); creates a new Point object (result) whose X and Y properties are the sum of the X and Y properties of obj1 and obj2. It uses the constructor method to create this new Point object with the summed coordinates.
Let us access the Point class and execute the code as shown below −
% Create two Point objects p1 = Point(1, 2); p2 = Point(3, 4); % Use the overloaded + operator p3 = p1 + p2; % Display the result disp(['X: ' num2str(p3.X) ', Y: ' num2str(p3.Y)]);
Here,
- p1 = Point(1, 2); creates a Point object p1 with X = 1 and Y = 2. Similarly, p2 = Point(3, 4); creates another Point object p2 with X = 3 and Y = 4.
- p3 = p1 + p2; uses the overloaded + operator to add p1 and p2, resulting in a new Point object p3 with X = 4 and Y = 6.
- The coordinates of p3 are displayed using disp.
On execution in matlab command window the output is −
>> % Create two Point objects p1 = Point(1, 2); p2 = Point(3, 4); % Use the overloaded + operator p3 = p1 + p2; % Display the result disp(['X: ' num2str(p3.X) ', Y: ' num2str(p3.Y)]); X: 4, Y: 6 >>
Example 2: Overloading the Minus Operator
Next, let's overload the - operator to subtract one point from another.
classdef Point properties X Y end methods function obj = Point(x, y) if nargin > 0 obj.X = x; obj.Y = y; end end % Overload the plus operator function result = plus(obj1, obj2) result = Point(obj1.X + obj2.X, obj1.Y + obj2.Y); end % Overload the minus operator function result = minus(obj1, obj2) result = Point(obj1.X - obj2.X, obj1.Y - obj2.Y); end end end
Save the above code in Point.m . Now, we can use the - operator with Point objects.
% Create two Point objects p1 = Point(5, 7); p2 = Point(2, 3); % Use the overloaded - operator p3 = p1 - p2; % Display the result disp(['X: ' num2str(p3.X) ', Y: ' num2str(p3.Y)]);
The output on execution in matlab command window is −
>> % Create two Point objects p1 = Point(5, 7); p2 = Point(2, 3); % Use the overloaded - operator p3 = p1 - p2; % Display the result disp(['X: ' num2str(p3.X) ', Y: ' num2str(p3.Y)]); X: 3, Y: 4
Example 3: Overloading the Multiply Operator
Finally, let's overload the * operator to scale a point by a scalar value.
if nargin > 0 obj.X = x; obj.Y = y; end end % Overload the plus operator function result = plus(obj1, obj2) result = Point(obj1.X + obj2.X, obj1.Y + obj2.Y); end % Overload the minus operator function result = minus(obj1, obj2) result = Point(obj1.X - obj2.X, obj1.Y - obj2.Y); end % Overload the mtimes operator function result = mtimes(obj, scalar) result = Point(obj.X * scalar, obj.Y * scalar); end end end
Now, we can use the * operator to scale a Point object.
% Create a Point object p = Point(3, 4); % Use the overloaded * operator to scale the point p2 = p * 2; % Display the result disp(['X: ' num2str(p2.X) ', Y: ' num2str(p2.Y)]);
The output on execution is as follows −
>> % Create a Point object p = Point(3, 4); % Use the overloaded * operator to scale the point p2 = p * 2; % Display the result disp(['X: ' num2str(p2.X) ', Y: ' num2str(p2.Y)]); X: 6, Y: 8 >>