Setting an object property using a method in Matlab
Asked Answered
W

1

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
Williswillison answered 16/3, 2011 at 2:49 Comment(0)
A
12

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
Alic answered 16/3, 2011 at 3:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.