matlabmatlab-class

Not able to work with properties in matlab class


The following MATLAB code does not work. I guess it has something to do that in the function changer, MATLAB tries to equal the objects A and B and not just setting the values to the same. Any workaround for that?

classdef foo
    %FOO Summary of this class goes here
    %   Detailed explanation goes here

    properties
        A=5
        B=0
    end

    methods
        function changer(obj)
            obj.B=obj.A
        end
    end

end

Solution

  • I think the code is actually working fine, just not doing quite what you expect.

    The way you've defined it, foo is a value class, so it has value semantics, rather than reference (or handle) semantics. When you execute changer(myobj), MATLAB is creating a copy of myobj with the new value of B and returning it to you. The original myobj remains unchanged. When implementing a value class, you would typically add an output argument to changer in order to be able to further work with this new copy.

    function obj = changer(obj)
    

    If you set foo to be a handle class, by inheriting from handle:

    classdef foo<handle
    

    it will then have reference (or handle) semantics, where the original myobj is modified (you then no longer need the output argument from changer):

    >> myobj = foo;
    >> changer(myobj); % or alternatively myobj.changer
    >> myobj.B
    ans =
         5