Matlab嵌套类,从内部引用同一类的对象

时间:2014-04-06 10:16:54

标签: matlab

我正在尝试在matlab中创建一个用于创建决策树的树类。当我尝试运行这个脚本时,第一次运行代码时,我可以看到它达到了F和V的有利值。但是,在左右新建节点的初始化之后,我甚至是当前对象为空。如何正确地将引用嵌套到类中的同一个类中,以便它们不会相互干扰

classdef dtree
properties (Access = public) 
    MaxDepth;
    CurrentDepth;
    Features;
    Left;
    Right;
    F;
    V;
end
  methods
      function this=dtree(md, cd, nf, Xtrain, Ytrain)
        % Now the real initialization begins
        this.MaxDepth = md
        this.CurrentDepth = cd;
        this.Features = nf;
        this.train(Xtrain, Ytrain);
      end

      function s = gini(dt, Labels)
        s = 1;
        s = s - (sum(Labels > 0.0) ./ numel(Labels)) ^ 2;
        s = s - (sum(Labels < 0.0) ./ numel(Labels)) ^ 2;
    end

    function train(dt, Xtrain, Ytrain)
        if (size(unique(Ytrain)) == 1 | dt.CurrentDepth > dt.MaxDepth)
            return;
        end

        minGINI = Inf;
        minF = 0;
        minV = Inf;
        for i = dt.Features
            for n = 1:size(Xtrain, 1)
                idx = Xtrain(:, i) > Xtrain(n, i);
                GINI = dt.gini(Ytrain(idx)) + dt.gini(Ytrain(~idx));
                if GINI < minGINI
                    minGINI = GINI;
                    minF = i;
                    minV = Xtrain(n, i);
                end
            end
        end
        dt.F = minF
        dt.V = minV
        lIdx = Xtrain(:, dt.F) > Xtrain(dt.V, dt.F);
        dt.Left = dtree(dt.MaxDepth, dt.CurrentDepth + 1, dt.Features,Xtrain(lIdx, :), Ytrain(lIdx))
        dt.Right = dtree(dt.MaxDepth, dt.CurrentDepth + 1, dt.Features, Xtrain(~lIdx, :), Ytrain(~lIdx));
     end
  end

ans = dtree(1,1,[2,5,6],XTrain,YTrain);

执行期间   具有属性的dtree:

    MaxDepth: 1
CurrentDepth: 1
    Features: [4 5 2]
        Left: []
       Right: []
           F: 5
           V: 7

执行后,当我输入ans时 ans =

带有属性的dtree:

    MaxDepth: 1
CurrentDepth: 1
    Features: [4 5 2]
        Left: []
       Right: []
           F: []
           V: []

在列车运行之前,这是一个空对象。

1 个答案:

答案 0 :(得分:0)

处理类方法时,需要显式传递并返回对象

function this = dtree(...)
   this = this.train(...)
end

function dt = train(dt, XTrain, YTrain)
...
end

如果您不这样做,则不会更新对您所拥有对象的引用。您总是需要在Matlab中更新引用!