3

If I run this code to create a simple class:

classdef myclass
    properties
        m = 2;
        n = m + 2;
    end
end

I get an error:

Undefined function or variable 'm'.
Error in myclass (line 1)
classdef myclass 

Why is this? I left out the constructor in this minimal example because a) the error still occurs if I put the constructor in, and b) I encountered this error in a unit testing class, and the constructor isn't called in such classes in MATLAB 2013b.

Michael A
  • 4,391
  • 8
  • 34
  • 61

3 Answers3

5

There is a note on this page that might explain the problem:

Note: Evaluation of property default values occurs only when the value is first needed, and only once when MATLAB first initializes the class. MATLAB does not reevaluate the expression each time you create a class instance.

I take this to mean that when you create a class instance, m is not yet initialized, hence you cannot use it to set the default for another property n.

The only way I can get it to work is if I declare m as a Constant property:

classdef myclass
    properties (Constant = true)
       m=2; 
    end
    properties
        n = myclass.m + 2;
    end
end

But that probably doesn't help if you want to change m.

chappjc
  • 30,359
  • 6
  • 75
  • 132
  • 1
    This actually works really well because I don't need to change `m` in my unit testing framework. Thank you! – Michael A Nov 22 '13 at 22:12
1

You could also move the initialization to the constructor:

classdef myclass
    properties
        m = 2;
        n;
    end
    methods
        function obj = myclass(obj)
            obj.n = obj.m + 2;
        end
    end
end
MattyG
  • 81
  • 3
-2

MATLAB defines the properties as classname.propertyname. Hence, if you change the code to the following, it should work.

classdef myclass
    properties
        m = 2;
        n = myclass.m + 2;
    end
end

Kind regards,