Open In App

Operator Overloading in MATLAB

MATLAB allows you to specify more than one definition for an operator in the same scope which is called Operator Overloading. We can redefine or overload most of the built-in operators available in MATLAB. It is basically a type of polymorphism in which an operator is overloaded to give user-defined meaning to it. By implementing operators that are appropriate to your class, we can integrate objects of our class into the MATLAB language. Almost any operator can be overloaded in MATLAB. For example, objects that contain numeric data can define arithmetic operations like +, *, -, / etc so that we can use these objects in arithmetic expressions. By implementing relational operators, you can use objects in conditional statements, like switch, and if statements.

Overloaded operators retain the original MATLAB precedence for the operator.



We can understand it clearly with the help of examples. The Multiplication class implements multiplication for objects of this class by defining a Multiplier method. Multiplier defines the multiplication of objects as the multiplication of the NumericData property values. The Multiplier method constructs and returns a multiplication object whose NumericData property value is the result of the multiplication.

Example 1:






% MATLAB code
classdef Multiplier
 properties
      NumericData
   end
   methods
      function obj = Multiplier(val)
         obj.NumericData = val;
      end
      function r = multiply(obj1,obj2)
         a = double(obj1);
         b = double(obj2);
         r = Multiplier(a * b);
      end
      function d = double(obj)
         d = obj.NumericData;
      end
   end
end

Output:

 

Explanation:

Now for better or proper understanding, we take another example. Here, the Subtracter class implements subtraction for objects of this class by defining a Subtracter method.

Example 2: 




% MATLAB code
classdef Subtracter
   properties
      NumericData
   end
   methods
      function obj = Subtracter(val)
         obj.NumericData = val;
      end
      function r = minus(obj1,obj2)
         a = double(obj1);
         b = double(obj2);
         r = Subtracter(a - b);
      end
      function d = double(obj)
         d = obj.NumericData;
      end
   end
end

Output:

 

Code explanation to take input and generate output :


Article Tags :