MATLAB - Functions Overloading



Function overloading in MATLAB allows you to create multiple functions with the same name but different input arguments. This is useful when you want a single function name to handle different types of input data or different numbers of input arguments, making your code more flexible and easier to use.

In MATLAB, function overloading is typically achieved by defining multiple methods within a class, where each method has a different signature (i.e., a different number or type of input arguments). MATLAB determines which method to call based on the number and types of arguments passed when the function is invoked.

Why Overload Functions in MATLAB?

Function overloading in MATLAB allows you to redefine existing MATLAB functions for your custom classes. This is particularly useful when you want objects of your class to behave like built-in MATLAB types. By implementing methods with the same names as existing MATLAB functions, you can −

  • Specialize Behavior for Custom Types: Make your custom objects interact with standard MATLAB functions in a natural way. For instance, you can define how your objects should respond to operations like addition, subtraction, or logical comparisons.
  • Enhance Functionality: Implement functions like plotting or data manipulation specifically tailored for your class. This can make working with your custom objects as intuitive as working with built-in MATLAB data types.
  • Modify Default Behaviors: Change how certain functions operate with your class objects. This can involve defining custom behavior for object creation, deletion, indexing, or other fundamental operations.

Implementing Overloaded MATLAB Functions

When you create a class in MATLAB, you can define methods that override existing MATLAB functions specifically for instances of that class. This is useful because it allows your custom objects to behave in ways that are tailored to their unique characteristics while still integrating smoothly with the MATLAB environment.

Here's how MATLAB handles function overloading and how you can implement it:

Determine Dominant Argument − When MATLAB needs to decide which version of a function to use, it looks at the "dominant argument."

  • If one of the arguments is an object of a specific class, MATLAB will check if that class has its own version of the function.
  • If such a method exists in the object's class, MATLAB will use it instead of the global function.

In simpler terms: When you pass an object to a function, MATLAB uses the function from that object's class, if available.

Method Overloading − To overload a MATLAB function, you need to.

  • Define a method in your class with the same name as the MATLAB function you want to overload.
  • Ensure the method accepts an object of your class as an argument so MATLAB knows to call this method for your objects.

Implementing the Overloaded Method

  • Inside the method, write the code necessary to perform the desired operations. You can access and manipulate the object's properties within this method.
  • Your method can produce similar results to the original MATLAB function, but it is not required to have the same input/output signature.

Examples of Function Overloading

Here are a few examples to illustrate this concept −

Example 1: Function Overloading by Number of Inputs

Consider a class MyMath that has overloaded methods for adding numbers. One method handles two input arguments, and another handles three input arguments.

classdef MyMath
    methods
        function result = add(~, a, b)
            result = a + b;
        end
        
        function result = add(~, a, b, c)
            result = a + b + c;
        end
    end
end

Save the above code as MyMath.m.

Let us now call the class and call the methods add as shown below −

obj = MyMath();
result1 = obj.add(1, 2);
disp(result1);  
result2 = obj.add(1, 2, 3);
disp(result2); 

The MyMath class has overloaded add methods. One method handles two inputs, while another handles three inputs. MATLAB determines which method to use based on the number of arguments provided.

An object of the class is created, and methods are called with different numbers of arguments. MATLAB automatically selects the appropriate method based on the number of arguments.

Example 2: Function Overloading by Type of Inputs

Now, let's create a function called describe that provides different outputs depending on whether the input is a numeric value or a string.

function output = describe(input)
    if isnumeric(input)
        % If the input is numeric, return a description of the number
        if input > 0
            output = 'Positive number';
        elseif input < 0
            output = 'Negative number';
        else
            output = 'Zero';
        end
    elseif ischar(input)
        % If the input is a string, return a description of the string
        output = ['This is a string: ', input];
    else
        error('Unsupported input type');
    end
end

isnumeric() checks if the input is a number.

ischar() checks if the input is a string.

% Describe a positive number
num_description = describe(10);

% Describe a string
str_description = describe('MATLAB');

On code execution in matlab the output is −

Example 3: Function Overloading by Data Types in Object-Oriented Programming

In MATLAB's object-oriented programming (OOP), function overloading can also occur with methods in classes. You can define methods that behave differently based on the class or data type of the input.

classdef Shape
    methods
        function describe(obj)
            disp('This is a generic shape.');
        end
    end
end

classdef Circle < Shape
    methods
        function describe(obj)
            disp('This is a circle.');
        end
    end
end

classdef Rectangle < Shape
    methods
        function describe(obj)
            disp('This is a rectangle.');
        end
    end
end

We define a base class Shape and two subclasses, Circle and Rectangle. Each class has its own describe() method, which is overloaded based on the object type.

shape = Shape();
circle = Circle();
rectangle = Rectangle();

shape.describe();       % Outputs: "This is a generic shape."
circle.describe();      % Outputs: "This is a circle."
rectangle.describe();   % Outputs: "This is a rectangle."
Advertisements