How to obtain static member variables in MATLAB classes?

后端 未结 4 1653
名媛妹妹
名媛妹妹 2020-12-03 03:36

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

This doesn\'t work:

classdef A

    properties ( Static )
        m = 0;
    end
         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 04:21

    Another workaround to get something like static properties is to use the fact that initialisation code for member variables is only executed once when the class file is loaded. That means, if you have a definition like

    classdef foo
        properties
            stuff = some_function()
        end
    end
    

    then some_function is invoked only once, and if it returns an object of class type, this will be shared by all instances. I've added a sample implementation that shows how that can be used:

    classdef ClassWithStaticMembers
        properties
            classvars = StaticVarContainer('foo', 0, 'bar', 2);
            othervar
        end
        methods
            function obj=ClassWithStaticMembers(var)
                obj.othervar = var;
            end
        end 
    end
    
    classdef StaticVarContainer < dynamicprops
        methods
            function obj=StaticVarContainer(varargin)
                for i=1:2:numel(varargin)
                    obj.addprop(varargin{i});
                    obj.(varargin{i}) = varargin{i+1};
                end
            end
        end
    end
    

    If you run this sample code

    obj1 = ClassWithStaticMembers(3);
    obj2 = ClassWithStaticMembers(5);
    obj1.classvars.foo = [2,3];
    
    obj1.othervar
    obj1.classvars
    
    obj2.othervar
    obj2.classvars
    

    you'll see, that classvars is indeed shared. I think this solution is much nicer than using persistent variables in functions, since you can reuse the StaticVarContainer as often as you want, it's easier to use, and furthermore, you directly see the initialisation of the static variables in the properties section.

    To get the result, that is desired in the OP's question (i.e. implementing an object counter) the shared property can be made Constant, so that it can be referenced without an instance at hand:

    classdef ClassWithCounter
        properties (Constant)
            static = StaticVarContainer('counter', 0);
        end
        methods
            function obj=ClassWithCounter()
                obj.static.counter = obj.static.counter + 1;
            end
        end 
    end
    
    clear all
    obj1 = ClassWithCounter();
    obj2 = ClassWithCounter();
    obj3 = ClassWithCounter();
    
    ClassWithCounter.static.counter
    

    Note, that the Constant attribute only means that, e.g. obj1.static cannot be changed, but it does not affect obj1.static.counter which is not constant, and can be set to heart's desire.

提交回复
热议问题