Iteratively print matlab struct

8 visualizaciones (últimos 30 días)
karthik varma
karthik varma el 24 de Mzo. de 2017
Comentada: Anoop Somashekar el 27 de Mzo. de 2017
I have a matlab struct with the following structure
Tree:
feature : numerical value (1)
tru: numerical value(2)
gain: numerical value(3)
left: struct with left node
right: struct with right node
How do i print this out int the for of a tree. for example i wanna print out for the root node
node 1 feature 1 , tru 2, gain 3
node 2 Contains data from left struct with the same structure as root node
node 3 contains data from right struct with the same structure as root node
i want to recursive print the entire tree using the same format
  2 comentarios
Jan
Jan el 27 de Mzo. de 2017
I do not understand the question. Can you post the code to create the struct in valuid Matlab syntax and create the wanted output manually?
Anoop Somashekar
Anoop Somashekar el 27 de Mzo. de 2017
I believe you want to recursively traverse the tree where each node of the tree is of type struct. Assuming that the tree is binary and the node structure only contains two nested structure of the same type(left and right), then you can simply define a function which recursively traverses the tree struct using isstruct property as shown:
function traverse(node)
if isstruct(node)
fprintf('%d %d\n', node.feat, node.gain);          
    if isstruct(node.left)
    traverse(node.left)
    end
    if isstruct(node.right)
    traverse(node.right)
    end
end
end
If the struct fields are dynamic then you could use fieldnames property to get all the fields of a given struct and getfield property to get the field value.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by