如何使用参考"进行#34;递归MatLab函数

时间:2015-12-02 18:10:11

标签: matlab

如标题中所述,我有一个递归函数,我正在尝试构建一个树数据结构来保存我的结果。每个节点只包含一个数字。问题是,当我将树输入到函数的下一次调用时,似乎只传递了树的值,而不是实际的树。有谁知道如何传递对树的引用?

初始通话:

tree = struct('left', 'empty','right', 'empty','feature','empty');
decisiontree_train(AttributeSet, LabelSet, 50, tree, 'node');

递归函数:

function decisiontree_train( data, labels, before_split_purity_percentage, tree, branch )

% a1 is 0, a2 is 1
[ a1_split_data, a2_split_data, a1_split_labels, a2_split_labels, ...
    split_feature ] = decisiontree_split( data, labels );

new_tree = struct('left', 'empty','right', 'empty','feature','empty');
if strcmp(branch, 'left')
    tree.left = new_tree;
    new_tree.feature = split_feature;
elseif strcmp(branch, 'right')
    tree.right = new_tree;
    new_tree.feature = split_feature;
elseif strcmp(branch, 'node')
    tree.feature = split_feature;
    new_tree = tree;
end

[ after_split_purity_percentage ] = decisiontree_classcount( a1_split_labels );
if after_split_purity_percentage < 100 && ...
        after_split_purity_percentage > before_split_purity_percentage
    decisiontree_train(a1_split_data, a1_split_labels, ...
        after_split_purity_percentage, new_tree, 'left');
end

[ after_split_purity_percentage ] = decisiontree_classcount( a2_split_labels );
if after_split_purity_percentage < 100 && ...
        after_split_purity_percentage > before_split_purity_percentage
    decisiontree_train(a2_split_data, a2_split_labels, ...
        after_split_purity_percentage, new_tree, 'right');
end

% add variable to workspace
% assignin('base', 'a1_split_data', a1_split_data)

end

1 个答案:

答案 0 :(得分:3)

除非你使用面向对象的matlab,否则没有通过引用传递。在问一个不同的问题时the answers somehow apply to your case as well。如果您使用的是Matlab 2015b或更新版本,请使用Matlab OOP并使用句柄类实现您的树。如果表现不是一个大问题,那就这样做吧。

由于两者都不正确的可能原因,你必须解决这个问题。 Matlab使用copy-on-write。因此,更改函数以将树结构作为第一个输入参数并返回修改它并不是一个坏主意。在典型情况下,只有非常少的数据被真正复制。