Home matlab how to call a class method that changes prop from another class method
Reply: 1

matlab how to call a class method that changes prop from another class method

pashute
1#
pashute Published in 2017-12-07 12:33:32Z

If I call a method (receiving and returning obj) it changes my property.

But if I call that method from another method it fails. I tried all kinds of ways but still failing.

 classdef AClass
  properties
    A;
  end
  methods 
    function obj = ChangeA(obj, v)
      obj.A = v;
    end
    function obj = CallChangeA(obj)
      obj.ChangeA(4);
      %obj = obj.ChangeA(4);
      %ChangeA(obj, 4);
      %obj = ChangeA(obj, 4);
      % none of these works
    end
  end
end

% ------ script: 
a1 = AClass;
a1.A = 1;
a1.ChangeA(2); % a1.A = 2

a2 = AClass;
a2.A = 3;
a2.CallChangeA(); % a2.A = 3 !!!  not four

How do I write the code so calling from 1 method to the other updates the property?

excaza
2#
excaza Reply to 2017-12-07 13:02:14Z

Other than the obvious typos in your example code, as I commented above, I would highly suggest taking a look at the difference between MATLAB's Handle and Value classes. By default, MATLAB classes are value classes, so each time the object is passed to a function an independent copy is created. If you're making changes to this object then you need to return it as an output:

classdef AClass
    properties
        A;
    end
    methods
        function obj = ChangeA(obj, a)
            obj.A = a;
        end

        function obj = CallChangeA(obj)
            obj = obj.ChangeA(4);
        end
    end
end

Which functions as expected:

>> a1 = AClass;
>> a1.A = 1

a1 = 

  AClass with properties:

    A: 1

>> a1 = a1.CallChangeA()

a1 = 

  AClass with properties:

    A: 4

Handle classes, on the other hand, are references to a single underlying object, allowing for (among other things) in place modification of the object:

classdef AClass < handle
    properties
        A;
    end
    methods
        function ChangeA(obj, a)
            obj.A = a;
        end

        function CallChangeA(obj)
            obj.ChangeA(4);
        end
    end
end

Which also functions as expected:

>> a1 = AClass;
>> a1.A = 1;
>> a1.A

ans =

     1

>> a1.CallChangeA()
>> a1.A

ans =

     4
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.302961 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO