Matlab - Function taking no arguments within a cla

2019-03-06 08:15发布

问题:

As I do not seem to be able to edit my old question (Matlab - Function taking no arguments but not static), here it is again:

I am trying to implement the following:

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

But I am getting the error that somefunction1 should be static. But if it's static then it can't access the properties anymore. How would I resolve this issue?

Basically I want to be able to write something like this:

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

as opposed to writing

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

回答1:

For accessing the properties of an object in a method, you need to pass that object as argument to the method. If you don't need a specific object in order to perform a function, then make it static (belongs to the class, but does not operate on a specific object).

So, compare the original code:

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

with the correct code:

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;

To call the method, you'd write indeed (please test):

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

because, in MATLAB, this is 99.99% of cases equivalent to:

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

The differences appear when you're overriding subsref for the class, or when the object passed to the method is not the first in the argument list (but these are cases that you should not concern with for now, until you clarify the MATLAB class semantics).