wzFelix
wzFelix

Reputation: 45

In matlab, I got different values in a method of class and out

In the matlab, I defined a class and instantiated the class in another script, but I got different values in and out of the method. My matlab code are shown bellow:

test_add.m

classdef test_add
    properties
        a
        b
    end
    methods
        function obj = test_add(a, b)
            obj.a = a;
            obj.b = b;
        end
        function c = add_1(obj)
            c = obj.a + 1;
        end
        function inter(obj, t)
            for i = 1:t
                obj.a = obj.add_1();
            end
            fprintf('In the method:\n');
            fprintf('a = %d\n',obj.a);
            fprintf('b = %d\n',obj.b);
            disp('=======================');
        end
    end
end

main.m

tt = test_add(1,2);
tt.inter(3);
fprintf('Out of the method:\n');
fprintf('a = %d\n',tt.a);
fprintf('b = %d\n',tt.b);

output:

In the method:
a = 4
b = 2
=======================
Out of the method:
a = 1
b = 2

Upvotes: 0

Views: 46

Answers (2)

Lior Cohen
Lior Cohen

Reputation: 5735

In Matlab there are two type of classes: handle class and Value class. If you said nothing you get the Value class. Most of the OO languages out there are using handle class semantic.

So, you have two options:

  1. Change you class to handle class by inheriting from handle

    classdef test_add < handle
    
  2. Stay with Value class and change your inter function to return obj.

    But then, in main call obj=tt.inter(3) to get the updated object.

     function obj = inter(obj, t)
                for i = 1:t
                    obj.a = obj.add_1();
                end
                fprintf('In the method:\n');
                fprintf('a = %d\n',obj.a);
                fprintf('b = %d\n',obj.b);
                disp('=======================');
            end
    

Upvotes: 2

wzFelix
wzFelix

Reputation: 45

It's a problem of value class vs handle class, the solution is:

test_add.m

classdef test_add < handle
    ...
end

Then, the output is:

In the method:
a = 4
b = 2
=======================
Out of the method:
a = 4
b = 2

Upvotes: 0

Related Questions