Constants in MATLAB

前端 未结 8 903
孤城傲影
孤城傲影 2020-12-04 21:44

I\'ve come into ownership of a bunch of MATLAB code and have noticed a bunch of \"magic numbers\" scattered about the code. Typically, I like to make those constants in lan

8条回答
  •  独厮守ぢ
    2020-12-04 22:08

    Matlab has constants now. The newer (R2008a+) "classdef" style of Matlab OOP lets you define constant class properties. This is probably the best option if you don't require back-compatibility to old Matlabs. (Or, conversely, is a good reason to abandon back-compatibility.)

    Define them in a class.

    classdef MyConstants
        properties (Constant = true)
            SECONDS_PER_HOUR = 60*60;
            DISTANCE_TO_MOON_KM = 384403;
        end
    end
    

    Then reference them from any other code using dot-qualification.

    >> disp(MyConstants.SECONDS_PER_HOUR)
            3600
    

    See the Matlab documentation for "Object-Oriented Programming" under "User Guide" for all the details.

    There are a couple minor gotchas. If code accidentally tries to write to a constant, instead of getting an error, it will create a local struct that masks the constants class.

    >> MyConstants.SECONDS_PER_HOUR
    ans =
            3600
    >> MyConstants.SECONDS_PER_HOUR = 42
    MyConstants = 
        SECONDS_PER_HOUR: 42
    >> whos
      Name             Size            Bytes  Class     Attributes
    
      MyConstants      1x1               132  struct              
      ans              1x1                 8  double              
    

    But the damage is local. And if you want to be thorough, you can protect against it by calling the MyConstants() constructor at the beginning of a function, which forces Matlab to parse it as a class name in that scope. (IMHO this is overkill, but it's there if you want it.)

    function broken_constant_use
    MyConstants(); % "import" to protect assignment
    MyConstants.SECONDS_PER_HOUR = 42 % this bug is a syntax error now
    

    The other gotcha is that classdef properties and methods, especially statics like this, are slow. On my machine, reading this constant is about 100x slower than calling a plain function (22 usec vs. 0.2 usec, see this question). If you're using a constant inside a loop, copy it to a local variable before entering the loop. If for some reason you must use direct access of constants, go with a plain function that returns the value.

    For the sake of your sanity, stay away from the preprocessor stuff. Getting that to work inside the Matlab IDE and debugger (which are very useful) would require deep and terrible hacks.

提交回复
热议问题