Node generation via recursion

9 views (last 30 days)
Ashish Kumar
Ashish Kumar on 3 Mar 2021
Answered: Shantanu Dixit on 30 May 2025
How can I create nodes recursively to generate tree in MATLAB
  2 Comments
Ashish Kumar
Ashish Kumar on 3 Mar 2021
Edited: Ashish Kumar on 3 Mar 2021
Is there any way to create nodes explicitly?
Actually I want to generate the tree using recursion with the help of nodes.

Sign in to comment.

Answers (1)

Shantanu Dixit
Shantanu Dixit on 30 May 2025
Hi Ashish,
If I understood the query, there are particularly two context where recursively generating nodes can apply.
  1. GUI based: Building a UI-based tree through recursion (using uitreenode)
  2. 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:
  1. Choose the best feature to split on (eg. Gini index or entropy)
  2. Recur on the data to create left and right branches (child nodes)
  3. 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!

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!