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

StackOverflow https://stackoverflow.com/questions/20154907

  •  04-08-2022
  •  | 
  •  

Question

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.

Was it helpful?

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.

OTHER TIPS

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

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,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top