Search code examples
matlabmatlab-class

Why does MATLAB throw an "undefined variable" error when I try to assign a class property to another class property in the properties block?


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.


Solution

  • 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.