Matlab - Function taking no arguments within a class

后端 未结 1 366
无人共我
无人共我 2021-01-26 10:02

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:

相关标签:
1条回答
  • 2021-01-26 10:10

    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).

    0 讨论(0)
提交回复
热议问题