8

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?

gnychis
  • 7,289
  • 18
  • 75
  • 113
  • See [matlab classes: handle or value](http://stackoverflow.com/questions/6436539/matlab-classes-handle-or-value) for a discussion of handle vs. value classes. – b3. Nov 10 '11 at 21:56

2 Answers2

14

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
gnovice
  • 125,304
  • 15
  • 256
  • 359
b3.
  • 7,094
  • 2
  • 33
  • 48
  • bingo! that worked perfectly, thanks so much :) I have to wait 4 minutes to select this as the answer, but will do – gnychis Nov 10 '11 at 21:55
  • 5
    It's important to mention that once the class becomes **handle**, variables to which this class was assign to become reference to the same object in memory. Changing a property in one of those variables will change property value in the others similarly to object reference in c# for instance. – Celdor Mar 25 '15 at 14:50
3

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);
abcd
  • 41,765
  • 7
  • 81
  • 98
  • 2
    To be clear: the example shown here is for a value object class (ie: not a handle object), and it does not change the property of the original object per se. The function receives a _copy_ of the original object in the N argument, modifies that object's some_var property, and returns the modified copy of the object. – gwideman Nov 15 '14 at 12:02