Reputation: 9
I am going to define a class in MATLAB called "Node" which is supposed to be a node of a tree structure.
I have a variable inside it called "NodeList" which is supposed to be a list of sub nodes.
Here is what I have defined:
classdef Node
properties
Title string %name
NodeType Type_Node %enum Design/Variation
NodeList cell{Node} %list of sub nodes
RelationType Relation %enum AND/OR
ImportanceFactor float %float [0 1]
NodeIndex {mustBePositive} %int for drawing the tree
end
methods
function obj=Node(title,nodetype,nodelist,relation,impactfactor,nodeindex)
obj.Title=title;
obj.NodeType=nodetype;
obj.NodeList=nodelist;
obj.RelationType=relation;
obj.ImportanceFactor=impactfactor;
obj.NodeIndex=nodeindex;
end
end
end
While instantiating the class I am getting this error message:
Error setting default value of property 'NodeList' of class 'Node'. The 'Node' class
definition uses an instance of itself directly
or indirectly as the default value for the 'NodeList' property. This is not allowed.
First, please let me know whether the syntax I have used to define the class is correct or not.
Then, I would appreciate any suggestions to make list of instances of a class.
Third, how can I nest a list of instances of the very class inside itself?
Upvotes: 0
Views: 236
Reputation: 12345
Try this as a next step. (I simplified the class, for my convenience)
classdef Node < handle
properties
Title string %name
NodeList Node %list of sub nodes
end
properties (Constant = true)
NullNode = Node();
end
methods
function obj=Node(varargin)
switch nargin
case 2
obj.Title=varargin{1};
obj.NodeList=varargin{2};
case 0
obj.Title = '';
obj.NodeList = obj;
end
end
end
end
Now these all work:
nFirst = Node()
nOther = Node('name', nFirst )
nWithAList = Node('list', [nFirst, nOther])
Changes that I made:
NodeList
validator is only to the Node
class, rather than cell{Node}
. This still allows a standard array of the class. (You can separately set size restrictions on the array if you want. [1])NullNode
object to put in here, depending on what makes sense in the project. Sample is defined in the code.)handle
. (This is not strictly needed to address your original question. However, based on the context of the sample code, I suspect this is closer the behavior you will expect.)[1] https://www.mathworks.com/help/matlab/matlab_oop/defining-properties.html (See "Property Validation Syntax")
Upvotes: 3