Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do properties not take on a new value from class method? [duplicate]

I am trying to understand a little bit more about Matlab classes and their properties. Here is a test class I have created:

classdef Test    
    properties
         % Properties of the network type
        some_var
    end

    methods
         function N = Test()
         end

        function change_var( N, val )
             N.some_var=val;
        end
    end
end

Now, I create an instance of this class, and call "change_var()"...

>> a=Test;
>> a.change_var(2);
>> a.some_var

ans =

     []

Why has the property "some_var" not taken on the value "val" in the assignment?

like image 884
gnychis Avatar asked Nov 10 '11 21:11

gnychis


2 Answers

The Test class has been defined as a value-class as opposed to a handle class. Effectively, when you call a.change_var, a is passed in by-value. To store the change to the some_var property do this:

>> a = Test;
>> a = a.change_var(2);

The alternative is to make Test a handle class in which case the example in your question would work as you expected. To do this, inherit from the handle class by changing the first line of your class definition to this:

classdef Test < handle
like image 183
b3. Avatar answered Sep 17 '22 16:09

b3.


The method provides for a way to change the property, but you should also return the object. You'll need to modify your method as:

function N = change_var( N, val )
     N.some_var=val;
end

Note that the function returns the modified object. Next, you'll need to update a with the change as:

a = a.change_var(2);
like image 20
abcd Avatar answered Sep 21 '22 16:09

abcd