1

I have a class MyData and a class Container

classdef MyData < handle
    properties
        x
    end

    methods
        function obj=MyData()
            obj.x=0;
        end
    end
end
classdef Container < handle
    properties
        myobject_array
    end

    methods
        function obj=Container(n)
            obj.myobject_array(n)=MyData();
        end
    end
end

When I want to construct a Container object by Container(3), the following error is thrown

The following error occurred converting from MyData to double:
Conversion to double from MyData is not possible.

Error in Container (line 8)
            obj.myobject_array(n)=MyData();

How can I write the constructor of Container to make a array of MyData object be constructed in Container object?

2 Answers 2

2

Change the Container constructor:

classdef Container < handle
    properties
        myobject_array
    end

    methods
        function obj = Container(n)
            MyObjectArray(n,1) = MyData;
            obj.myobject_array = MyObjectArray;
        end
    end
end

or:

classdef Container < handle
    properties
        myobject_array
    end

    methods
        function obj = Container(n)
            obj.myobject_array = MyData.empty;
            obj.myobject_array(n,1) = MyData();
        end
    end
end

>> c = Container(3);
>> c.myobject_array

ans = 

  3×1 MyData array with properties:

    x
Sign up to request clarification or add additional context in comments.

3 Comments

It works, sir, could you please tell me why we can not directly assign on obj.myobject_array? It seems that by defalut the obj.myobject_array is double. Can we told the matlab that the type of obj.myobject_array should be MyData?
I believe the answer by @Cris addresses that.
@XuHui I've also added another possible solution
1

Another solution is to provide a default value for the property:

classdef Container < handle
    properties
        myobject_array = MyData;
    end

    methods
        function obj=Container(n)
            obj.myobject_array(n) = MyData;
        end
    end
end

(Note that you do not need to provide empty parentheses, MyData is the same as MyData(). It is traditional in MATLAB to not add the empty parentheses.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.