How to obtain static member variables in MATLAB classes?

后端 未结 4 1650
名媛妹妹
名媛妹妹 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:10

    Here's a direct way to create a static property in Matlab. The only difference between this implementation and a hypothetical (but impossible; see Mikhail's answer) true static property is the syntax for setting the member variable.

    classdef StaticVarClass
        methods (Static = true)
            function val = staticVar(newval)
                persistent currentval;
                if nargin >= 1
                    currentval = newval;
                end
                val = currentval;
            end
        end
    end
    

    Now the static property staticVar can be read via:

    StaticVarClass.staticVar
    

    ...and be set via:

    StaticVarClass.staticVar(newval);
    

    So, for instance, this is the expected output from a test of this functionality:

    >> StaticVarClass.staticVar
      ans =
          []
    >> StaticVarClass.staticVar('foobar')
      ans =
          foobar
    >> StaticVarClass.staticVar
      ans =
          foobar
    >> 
    

    This approach works just as well for private static properties like you requested, but the demo code is a little longer. Note that this is not a handle class (though it would work perfectly well on a handle class as well).

    classdef StaticVarClass
        methods (Access = private, Static = true)
            function val = staticVar(newval)
                persistent currentval;
                if nargin >= 1
                    currentval = newval;
                end
                val = currentval;
            end
        end
    
        methods
            function this = setStatic(this, newval)
                StaticVarClass.staticVar(newval);
            end
    
            function v = getStatic(this)
                v = StaticVarClass.staticVar;
            end
        end
    end
    

    ...and the test:

    >> x = StaticVarClass
      x = 
          StaticVarClass with no properties.
          Methods
    >> x.getStatic
      ans =
          []
    >> x.setStatic('foobar')
      ans = 
          StaticVarClass with no properties.
          Methods
    >> x.getStatic
      ans =
          foobar
    >> 
    

提交回复
热议问题