Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing Static Functions in Matlab

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?

like image 352
kevmo314 Avatar asked May 02 '26 19:05

kevmo314


1 Answers

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!
like image 96
Florian Brucker Avatar answered May 05 '26 12:05

Florian Brucker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!