Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an object property using a method in Matlab

I am creating a class in MATLAB and while I have little experience with objects, I am almost positive I should be able to set a class property using a class method. Is this possible in MATLAB?

classdef foo
    properties
        changeMe 
    end

    methods
        function go()
          (THIS OBJECT).changeMe = 1;
        end
    end
end

f = foo;
f.go;


t.changeMe;
ans = 1
like image 696
user516677 Avatar asked Mar 16 '11 02:03

user516677


People also ask

What are methods in MATLAB?

Methods are the operations defined by a class. Methods can overload MATLAB® functions to perform the operations on objects of the class. MATLAB determines which method or function to call based on the dominant argument. Class constructor methods create objects of the class and must follow specific rules.


1 Answers

Yes, this is possible. Note that if you create a value object, the method has to return the object in order to change a property (since value objects are passed by value). If you create a handle object (classdef foo<handle), the object is passed by reference.

classdef foo
    properties
        changeMe = 0;
    end

    methods
        function self = go(self)
          self.changeMe = 1;
        end
    end
end

As mentioned above, the call of a setting method on a value object returns the changed object. If you want to change an object, you have to copy the output back to the object.

f = foo;
f.changeMe
ans =
   0

f = f.go;

f.changeMe
ans =
   1
like image 177
Jonas Avatar answered Oct 22 '22 04:10

Jonas