Referencing Static Functions in Matlab

126 views Asked by At

For an object in MATLAB, is it possible to call a static function of the same type without knowing the encompassing package? Right now, the only way I've found to reference it is to use Package.Whatever.staticfunction(), but I'd like to properly encapsulate the class by having it operate independent of whatever package it's in.

The solution I've found right now is:

classdef Whatever
    methods(Static)
        function fig = staticfunction()
             ...snip...
        end
    end
    methods
        function obj = Whatever()
            % Call Package.Whatever.staticfunction();
            eval(sprintf('%s.staticfunction();', class(obj)));
        end
    end
end

but this seems clunky, slow, and incorrect. Is there a better way to do it?

1

There are 1 answers

1
Florian Brucker On BEST ANSWER

You can simply use the instance to call the static method. This looks like a non-static method call, but it's not:

classdef StaticTest

    methods (Static)        
        function doStatic()
            fprintf('Static!\n');
        end
    end

    methods
        function obj = StaticTest()
            obj.doStatic()
        end

        function obj = doNotStatic(obj)
            fprintf('Not static!\n');
            obj.doStatic();
        end
    end

end

Usage:

>> x = StaticTest();
Static!
>> x.doNotStatic();
Not static!
Static!