Matlab - 函数在类中不带参数

时间:2014-07-04 15:36:00

标签: matlab function class

因为我似乎无法编辑我的旧问题(Matlab - Function taking no arguments but not static),所以这里又是:

我正在尝试实施以下内容:

classdef asset
    properties
        name
        values
    end    

    methods

        function AS = asset(name, values)
            AS.name = name;
            AS.values = values;
        end

        function out = somefunction1
            ret = somefunction2(asset.values);
            out = mean(ret);
            return
        end

        function rets = somefunction2(vals)
            n = length(vals);
            rets = zeros(1,n-1);
            for i=1:(n-1)
                rets(i) = vals(i)/vals(i+1);
            end
            return
        end
    end
end

但我得到的错误是somefunction1应该是静态的。但如果它是静态的,那么它就不能再访问这些属性了。我该如何解决这个问题?

基本上我希望能够写出这样的东西:

AS = asset('testname',[1 2 3 4 5]);
output = AS.somefunction1();

而非写作

AS = asset('testname',[1 2 3 4 5]);
output = AS.somefunction1(AS);

1 个答案:

答案 0 :(得分:1)

要访问方法中对象的属性,需要将该对象作为参数传递给方法。如果您不需要特定对象来执行某个功能,那么请将其设置为静态(属于该类,但不对特定对象进行操作)。

所以,比较原始代码:

methods

    % ...

    function out = somefunction1
        ret = somefunction2(asset.values);
        out = mean(ret);
        return
    end;

    function rets = somefunction2(vals)
        n = length(vals);
        rets = zeros(1,n-1);
        for i=1:(n-1)
            rets(i) = vals(i)/vals(i+1);
        end
        return
    end
end

使用正确的代码:

methods

    % ...

    % this function needs an object to get the data from,
    % so it's not static, and has the object as parameter.

    function out = somefunction1(obj)
        ret = asset.somefunction2(obj.values);
        out = mean(ret);
    end;
end;

methods(Static)
    % this function doesn't depend on a specific object,
    % so it's static.

    function rets = somefunction2(vals)
        n = length(vals);
        rets = zeros(1,n-1);
        for i=1:(n-1)
            rets(i) = vals(i)/vals(i+1);
        end;
    end;
end;

要调用该方法,您确实要写(请测试):

AS = asset('testname',[1 2 3 4 5]);
output = AS.somefunction1();

因为,在MATLAB中,99.99%的案例相当于:

AS = asset('testname',[1 2 3 4 5]);
output = somefunction1(AS);

当您为类重写subsref时,或者传递给方法的对象不是参数列表中的第一个(但这些是您不应该关注的情况)时,会出现差异现在,直到你澄清MATLAB类语义)。