recursively traverse a struct in matlab

To recursively traverse a struct in MATLAB, you can use a recursive function that calls itself on each sub-struct that it encounters. Here is an example function that traverses a struct and prints the names of each field:

main.m
function traverse_struct(s)

fields = fieldnames(s);

for i = 1:numel(fields)
    fieldname = fields{i};
    value = s.(fieldname);
    if isstruct(value)
        traverse_struct(value); % recursive call
    end
    disp(fieldname);
end

end
242 chars
15 lines

You can call this function with a struct as its input argument:

main.m
s = struct('field1', 1, 'field2', struct('field3', 2, 'field4', 3));
traverse_struct(s);
89 chars
3 lines

This will print the following output:

main.m
field1
field3
field4
field2
28 chars
5 lines

gistlibby LogSnag