How to obtain static member variables in MATLAB classes?

Viewed 15862

Is there a way to define static member variables in MATLAB classes?

This doesn't work:

classdef A

    properties ( Static )
        m = 0;
    end
end

It suggests to use keyword "Constant" instead of "Static", the constant properties cannot be modified. I want a variable common to all objects of class A and I want to be able to modify that variable in methods of class A.

So what I need is a private static member variable. Is there a way to obtain it in MATLAB?


Found out that a workaround can be done using persistent variables in static member functions.

In this case you should inherit all your classes from a base class like the following.

classdef object < handle

    properties ( GetAccess = 'public', SetAccess = 'private' )
        id
    end

    methods ( Access = 'protected' )
        function obj = object()
            obj.id = object.increment();
        end
    end

    methods ( Static, Access = 'private' )
        function result = increment()
            persistent stamp;
            if isempty( stamp )
                stamp = 0;
            end
            stamp = stamp + uint32(1);
            result = stamp;
        end
    end  
end
4 Answers
Related