How to make a generic constructor in Matlab class - Matlab OOP 7 | applied electronics engineering

Latest

How to make a generic constructor in Matlab class - Matlab OOP 7

By Applied Electronics - Wednesday, February 8, 2017 No Comments
Here we show how to make a generic constructor in Matlab class. That is a constructor that accepts variable length input arguments list and acts according to the argument passed to the constructor. This can be done using varargin which stands for variable length input arguments list.

This is a continuation of object oriented programming with Matlab.

Following is an example of how we can create a general constructor that accepts variable number of arguments.

classdef player
    
    properties
        name;
        age;
    end
    
    methods
        function pObj = player(varargin)
            if nargin == 0
                pObj.name = 0;
            elseif nargin == 1
                pObj.name = varargin{1};
            else
                pObj.name = varargin{1};
                pObj.name = varargin{2};
            end
        end
    end
    
end

In the user class player, the constructor uses varargin as input argument instead of val1, val2 in the previous examples - User defined class and object in Matlab - Matlab OOP 5 and Properties and Methods of Object Oriented Programming Class - Matlab OOP 6.

The benefit is we don't have to specify the variables like var1, var2 etc into the arguments. The varargin takes care of it. Instead of assigning object properties to var1, var2 etc we can now do the exact same assignment using varargin{1}, varargin{2} etc. This translate to easier working while creating objects or instances. Consider the following code:

>> player1 = player

player1 = 

  player with properties:

    name: []
     age: []

>> player1 = player('jon')

player1 = 

  player with properties:

    name: 'jon'
     age: []

>> player1 = player('ron', 20)

player1 = 

  player with properties:

    name: 'ron'
     age: 20

>> player1.name

ans =

ron

>> player1.age

ans =

    20

When we don't specify any argument then the properties are empty. Then when we supply one argument the first property, the name, is updated but the second property remains empty. And if we specify two arguments, the first becomes the 1st property(name) and the second becomes the 2nd property(age).

So in this way we can make a general constuctor in Matlab class.

No Comment to " How to make a generic constructor in Matlab class - Matlab OOP 7 "