Adding methods to class in Matlab - Matlab OOP 8 | applied electronics engineering

Latest

Adding methods to class in Matlab - Matlab OOP 8

By Applied Electronics - Wednesday, February 8, 2017 No Comments
In this part of the Object Oriented Programming with Matlab tutorial we show how to add methods to class in Matlab.

Adding properties to classes and defining a constructor has already been illustrated in the previous tutorials:
 We will use the previous example of class person and is reshown below:

 
classdef player
    
    properties
        name;
        age;
    end
    
    methods
        function pObj = player(var1, var2)
            if nargin == 2
                pObj.name = var1;
                pObj.age = var2;
            end
        end
    end
    
end

To add a new method we have to add a new user defined function. Let say we want to add a method that displays the player information. Lets call this new method pinfo. So we can add this new method in the following way.

 
classdef player
    
    properties
        name;
        age;
    end
    
    methods
        function pObj = player(var1, var2)
            if nargin == 2
                pObj.name = var1;
                pObj.age = var2;
            end
        end
        
        function [] = pinfo(pObj)
            if nargin > 0
                fprintf('Name = %s\n', pObj.name);
                fprintf('Age = %d\n', pObj.age);
            end
        end
    end
    
end

Now we illustrate the usage of the new method pinfo by creating an object player1.

 
>> player1 = player;
>> player1.name = 'jon';
>> player1.age = 20;

where we specified the name and age for player1.

Now the method pinfo can be invoked for player1 object as follows:

 
>> player1.pinfo
Name = jon
Age = 20

No Comment to " Adding methods to class in Matlab - Matlab OOP 8 "