views:

975

answers:

5

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 languages like C, Ruby, PHP, etc. When googling this problem, I found that the "official" way of having constants is to define functions that return the constant value. Seems kludgey, especially because Matlab can be finicky when allowing more than one function per file.

Is this really the best option?

I'm tempted to use / make something like the C Preprocessor to do this for me. (I found that something called mpp was made by someone else in a similar predicament, but it looks abandoned. The code doesn't compile, and I'm not sure if it would meet my needs.)

+1  A: 

You might some of these answers useful. But in short, no there is not a "one-line" way of specifying variables whose value shouldn't change after initial setting in MATLAB.

mtrw
+6  A: 

I usually just define a variable with UPPER_CASE and place near the top of the file. But you have to take the responsibly of not changing its value.

Otherwise you can use MATLAB classes to define named constants.

Amro
I typically use a MATLAB class to hold all of my configurable parameters. This also gives you the ability to create multiple configurations and swap them in and out easily. You can even make an array of configurations and iterate through the array, running your test code on each configuration in turn.
bta
A: 

Any way you do it, it will still be somewhat of a kludge. In past projects, my approach to this was to define all the constants as global variables in one script file, invoke the script at the beginning of program execution to initialize the variables, and include "global MYCONST;" statements at the beginning of any function that needed to use MYCONST. Whether or not this approach is superior to the "official" way of defining a function to return a constant value is a matter of opinion that one could argue either way. Neither way is ideal.

+5  A: 

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.

Andrew Janke
I'd *love* to use the OOP stuff introduced in the newer versions of Matlab, but it makes things **depressingly slow** in our tests. (Running a *simple* function 100,000 times went from taking 0.0837 seconds to 2.3689 seconds when changing from nested functions to the OOP stuff.) Most of the stuff we write needs to be fairly optimized, so that overhead is quite deterring.
Benjamin Oakes
(I can post the code if you'd like.)
Benjamin Oakes
I hear ya. (See the other linked Q on OOP performance.) I use it sparingly, for the same reason. You can mix and match: put constants in a classdef for organization, and keep the rest of your code in functions or old style (faster) OOP. Overhead is per call; introducing OOP doesn't make existing non-OOP code slower. Pull the constant into a local variable before entering tight loops and it may be all right. Barring that, functions returning constant values is the idiomatic pre-2008a way to do constants, and what I'd suggest.
Andrew Janke
+1  A: 

MATLAB doesn't have an exact const equivalent. I recommend NOT using global for constants - for one thing, you need to make sure they are declared everywhere you want to use them. I would create a function that returns the value(s) you want. You might check out this blog post for some ideas.

Loren

related questions