Search code examples
matlabclasstyping

How to make property definition using own class in Matlab?


In Matlab I have the package "+mypackage". All the following definitions are under this folder/package.
MyClass.m

classdef MyClass
    properties
        prop1 MyProperty
    end
    
    methods (Static)
        function obj = with_five()
            obj = mypackage.MyClass(5);
        end
    end
    
    methods
        function obj = MyClass(num)
            obj.prop1 = mypackage.MyProperty(num);
        end
    end
end

MyProperty.m

classdef MyProperty    
    properties
        num double
    end
    
    methods
        function obj = MyProperty(val)
            obj.num = val;
        end
    end
end

So in MyClass.m I define the prop1 property to be an object of class MyProperty.
Now I would like to create objects with this script.

import mypackage.MyClass

class_test1 = MyClass(5);
class_test2 = MyClass.with_five();

When I run it I get following errors:

Error using Testpackage (line 3)
Error defining property 'prop1' of class 'mypackage.MyClass':
Class named 'MyProperty' is undefined or does not support property validation.

When I remove the property definition from MyClass.m it works. Is there a way to define properties to be an object of an own class in Matlab?


Solution

  • Thank you Wolfie your Help! I changed the definition for prop1 to mypackage.MyProperty.
    My Class definition looks now like this:

    classdef MyClass
        properties
            prop1 mypackage.MyProperty
        end
        
        methods (Static)
            function obj = with_five()
                obj = mypackage.MyClass(5);
            end
        end
        
        methods
            function obj = MyClass(num)
                obj.prop1 = mypackage.MyProperty(num);
            end
        end
    end
    

    Its necessary to point to MyProperty inside my package mypackage.
    Otherwise Matlab is not able to find it.
    I found it in the Matlab help: https://de.mathworks.com/help/matlab/matlab_oop/scoping-classes-with-packages.html?s_tid=srchtitle#brfynt_-3