TyanTowers
TyanTowers

Reputation: 160

Tree modification in matlab

I have a tree made of structures like:

node = 
   value: 4
   sub:   [1x4 struct]

where each sub is also a node.

node.sub(1) = 
    value: 6
    sub:   [1x4 struct]

etc. with leaf nodes having empty sub.

I want to write a function which changes the value of a particular node, like so:

function tree = ChangeValue(tree, path, value)
    % assume length(path) = 3 here
    tree.sub(path(1)).sub(path(2)).sub(path(3)).value = value;
end

How do I implememnt this if the length of path is not known?

note: According to Equality of structure objects I can do this by using handle classes. But I don't want to modify the way the tree is written. I can add elements to the structures, but I can't make them classes, or use an array of parents etc. for representing the tree because the tree is the output of a vlfeat function (vl_hikmeans)

Upvotes: 0

Views: 37

Answers (1)

Suever
Suever

Reputation: 65460

You could do this with a recursive function which will call itself passing itself the subtree as well as the remaining parts of the path. When the path is empty (i.e. you are at the end), it will assign the value.

function tree = ChangeValue(tree, path, value)
    if isempty(path)
        tree.value = value;
    else
        % Store the modified node        Pass the node    Remaining Path
        %     V                                V                V
        tree.sub(path(1)) = ChangeValue(tree.sub(path(1)), path(2:end), value);
    end
end

Upvotes: 1

Related Questions