Node generation via recursion
9 views (last 30 days)
Show older comments
How can I create nodes recursively to generate tree in MATLAB
2 Comments
Answers (1)
Shantanu Dixit
on 30 May 2025
Hi Ashish,
If I understood the query, there are particularly two context where recursively generating nodes can apply.
- GUI based: Building a UI-based tree through recursion (using uitreenode)
- Decision Tree Splitting: Recursively splitting the nodes based on the best feature from the data
GUI based: If you're working with hierarchical data (like a folder structure or a nested JSON), you can use recursion to dynamically add child nodes to a tree in the UI.
Here's a general idea of how you can approach this using 'uitree' and 'uitreenode' for a nested structure:
%{
dataStruct
├── A
│ ├── A1
│ └── A2
└── B
├── B1
└── B2
%}
dataStruct = struct('A', struct('A1', [], 'A2', []), 'B', struct('B1', [], 'B2', []));
% Create the root UI tree
t = uitree('Parent', uifigure);
root = uitreenode(t,'Text','root');
% Recursive function to add nodes
function addNodes(parentNode, s)
fields = fieldnames(s);
for i = 1:numel(fields)
child = uitreenode(parentNode, 'Text', fields{i});
if isstruct(s.(fields{i}))
addNodes(child, s.(fields{i})); % Recursive call
end
end
end
addNodes(root, dataStruct);
Decision Tree Splitting: In MATLAB the recursive tree splitting for decision tree's is usually abstracted through the method calls like 'tree = fitctree(X, Y)'. However if you want to manually implement the decision tree splitting criteria you can:
- Choose the best feature to split on (eg. Gini index or entropy)
- Recur on the data to create left and right branches (child nodes)
- Stop when a stopping condition is met (pure node / max depth)
Additionally you can refer to the following documentation of App building in MATLAB for more information:
Hope this helps!
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!