Constants in MATLAB

53,789

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

You might some of these answers How do I create enumerated types in MATLAB? 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.

Solution 5

My way of dealing with constants that I want to pass to other functions is to use a struct:

% Define constants
params.PI = 3.1416;
params.SQRT2 = 1.414;

% Call a function which needs one or more of the constants
myFunction( params ); 

It's not as clean as C header files, but it does the job and avoids MATLAB globals. If you wanted the constants all defined in a separate file (e.g., getConstants.m), that would also be easy:

params = getConstants();
Share:
53,789
Benjamin Oakes
Author by

Benjamin Oakes

Ruby, JavaScript, and Web. If I made a contribution that helped you, please consider Flattr logo http://api.flattr.com/button/flattr-badge-small.png leaving a tip via Flattr. Maid I maintain the open source Maid project: Be lazy. Let Maid clean up after you, based on rules you define. It's easy to install on a Mac or Linux. See instructions at http://rubygems.org/gems/maid TabCarousel I maintain an open source Chrome extension to help you keep tabs on info you want to monitor. Great for a TV or other external display. Install it from the Chrome Web Store.

Updated on February 09, 2020

Comments

  • Benjamin Oakes
    Benjamin Oakes about 4 years

    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.)

  • bta
    bta over 14 years
    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.
  • Benjamin Oakes
    Benjamin Oakes over 14 years
    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.
  • Andrew Janke
    Andrew Janke over 14 years
    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.
  • Nathan Donnellan
    Nathan Donnellan about 12 years
    I noticed Andrew recently did an update on Matlab speed. Probably more helpful than mine: stackoverflow.com/questions/1693429/…
  • Floris
    Floris almost 11 years
    "Deep and terrible hacks" - one of the most ominous phrases I have every heard when dealing with software. I consider myself warned!
  • ensignr
    ensignr over 6 years
    Trust Matlab to take something that is a simple, intrinsic part of almost every programming language and completely screw it up. The sooner Matlab dies a painful death the better IMHO.