9

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

1 Answer 1

13

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.