Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic matlab class method [duplicate]

Tags:

class

matlab

Possible Duplicate:
How to modify properties of a Matlab Object

I'm trying to convert my C# code into Matlab, in Matlab I decided to use OOP, which I haven't been used with Matlab, to be able to handle with the complexity of my C# code.

Looking the tutorial, I come up with the following code:

classdef Cat
    properties
        meowCount = 0; 
    end
    methods 
        function Meow(C)
            disp('meowww'); 
            C.meowCount = C.meowCount + 1;
        end
    end    
end

The result:

>> c = Cat();
>> c.Meow();
meowww
>> c

c = 

  Cat

  Properties:
     meowCount: 0

  Methods

So, meowCount does not change. What is the problem?

like image 618
Sait Avatar asked Feb 20 '23 10:02

Sait


1 Answers

A few problems I noticed:

  • you have no constructor
  • you do not derive from the handle base class

The constructor is not strictly necessary, but very useful to get to know for when you really want to start developing larger classes. It is used to initialize the obj object, which gets passed around to each and every method. It is quite similar to Python's self, or C++'s this.

So, your corrected class:

classdef Cat < handle

    properties
        meowCount = 0; 
    end

    methods 

        function obj = Cat()
            % all initializations, calls to base class, etc. here,
        end

        function Meow(obj)
            disp('meowww'); 
            obj.meowCount = obj.meowCount + 1;
        end
    end    
end

Demonstration:

>> C = Cat;
>> C.Meow; 
meowww
>> C.meowCount
1
like image 128
Rody Oldenhuis Avatar answered Mar 06 '23 01:03

Rody Oldenhuis