Skip to Main Content Skip to Search
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Loren on the Art of MATLAB

September 13th, 2006

Constants

Users have occasionally asked how to create and use constants in MATLAB. Here's one such example. In some cases, they would like to create a constant that other users or programs can't change. Unlike programming languages such as C, MATLAB doesn't have a declaration that enables this. Instead, we have constants, such as pi, defined as functions. When they get used once in a function, their value can't then be overwritten elsewhere in that function. You can use this same technique to make your own constant values.

Contents

Motivation

Suppose you're doing some calculations in quantum physics and you need to use Planck's constant h:

Solutions

There is no syntax in MATLAB for constant definition. You can place the value for h in each M-file that needs to use it. This becomes both tedious and potentially very error-prone, especially if you type as poorly as I sometimes do.

Alternatively, you can create a function M-file, such as this one

dbtype planck
1     function h = planck
2     %Planck Planck's constant.
3     h = 6.626068e-34; % Units are m^2 kg / s

and use it when you need Planck's constant. If instead you have a constant value that needs to be computed, you can store it in the M-file in a persistent variable and only calculate it the first time the function gets called. This is essentially the way pi works in MATLAB except its value is computed once at startup time and then is available throughout your MATLAB session.

Starting in R14 (MATLAB 7), you can't use a name in a function as both a variable and function so people can't overwrite the M-file version, provided they call your function first. E.g., this code generates a runtime error because of planck being an M-file and then trying to be a variable:

dbtype quantum
% and here's the error you would see
try
    quantum
catch
    err = lasterror;
    disp(err.message)
end
1     function y = quantum(x)
2     %Quantum  Very fake quantum calculation.
3     % Run the function.
4     h = planck;
5     % Now try to place the result in a variable and update it.
6     planck = planck+1;
7     % Do some calculation.
8     y = x*h + planck;
9     

Error: File: H:\Documents\LOREN\MyJob\Art of MATLAB\quantum.m Line: 6 Column: 1
 "planck" previously appeared to be used as a function or command,
 conflicting with its use here as the name of a variable.
 A possible cause of this error is that you forgot to initialize the
 variable, or you have initialized it implicitly using load or eval.

You also get an M-Lint message in the editor in quantum. Running mlint on quantum, we see a message telling us that we are using the name planck apparently before it is defined.

mlintMsg = mlint('quantum')
mlintMsg = 
    message: 'The variable 'planck' can apparently be used before it is defined.'
       line: 4
     column: [5 10]

Since mlint currently performs a static analysis of M-file code, without using information about the rest of the MATLAB environment, including the path, the analysis thinks that a variable is being used here since it's set on the left-hand side, but then it sees that we are using that variable on line 4, before we have a value for it.

What's not solved by placing constants in functions?

Some users would like to ensure that certain inputs to functions not be overwritten during the function execution. Currently there is not a bullet-proof way to guarantee this in MATLAB. Is that something you miss from other languages? Have you had uses for constants in your code? And have you been able to protect them adequately using the technique I outlined here, or perhaps some other one? I'd love to hear more about what needs you have regarding dealing with constants in MATLAB.


Published with MATLAB® 7.3

8 Responses to “Constants”

  1. wmar replied on :

    I do a lot of physcial science calculations, so I have a lot of constants for mass of electron, hbar, Boltzmann’s constant, etc. To get around typing it each time, I call an m-file script called fundamentalconstants.m to declare those variables every time I need fundamental constants. Persistent variables are interesting, hopefully that’ll protect me from overriding the value. I never really had a problem with overriding them though.

  2. Michael Wild replied on :

    What I’d like to see is some features allowing to

    a) restrict the data type (and array shape/size?) on function arguments. Testing with IS*, NDIMS and SIZE sometimes becomes very tedious.

    b) specify that a function argument is intended to be CONST. A syntax like

    function fun( const a )

    would be useful.

    c) override the copy-on-write-semantics, meaning that I want to modify the value of the argument itself, not a copy. If I want to have a function which changes a certain variable, currently I have to do convolutions such as
    a = fun(a)
    which, is bound to be inefficient. However, I don’t think it would be a good idea to introduce “real” reference parameters (such as C/c++ do), as this would change the semantics of Matlab programs too much. Perhaps a syntax could be devised to force the user to use the same name for input and output and then give Matlab a cue to handle the argument as a reference and not apply copy-on-write. A syntax like this might do it:

    function [a,b,c] = fun( ref a, b, c )

    where only “a” would be protected from copy-on-write.

  3. Raul Rato replied on :

    For clarity, I’m used to define CONSTANTS in my code, instead of “magic buried numbers”.

    I like simple solutions.
    I’d like to see a keyword, mconstant, for example, that
    allow the folowing construct:

    mconstant TWO__PI +6.28;

  4. Steve replied on :

    How I have handled this in the past was to create a script will all the constants I cared about. I usually named it ConstantsInclude because I really wish the C-like functionality was in matlab. I then called the script at the top of every function I created. The advantage of this was that I only had to define constants in one file. The problems are
    1) The constants weren’t protected within a function (I didn’t really care too much about this), and
    2) The overhead was huge. For mainy functions, the include script (which defined ~200 constants) took longer than the function. (This was the part that really bugged me)

    The overhead is less if all the constants were is a structure (i.e. Constant.PI, Constant.TWOPI), but that makes the code a little gross.

    I would be much happier (and swear a little less at Matlab) if you could define constants like in C, that would be handled before runtime.

  5. Joe Lotz replied on :

    Have have used the .m file include like the previous posters suggested, however, I agree with Steve about the overhead. I have done some testing and found that if you save your constants to a .mat data file and then call that instead of a script the overhead is reduced.

    Once again, this does not prevent overwriting as does the function definition technique. I agree and wish you could define constants and “lock” them.

  6. Joe Lotz replied on :

    Not to spam this comment board, but a quick search in FEX turned up this
    http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=13622&objectType=file

    It is an iteresting script that allows you to define constants What it does is automatically create functions like the technique suggested by Loren such that you get an error if you try to use a variable of the same name.

    I’ve only briefly looked at the code so cannot comment to its limitations but it looks useful.

  7. Greg Holley replied on :

    The trick about not being able to overwrite a function once you’ve called it is a useful one. I imagine I could declare constants via some mechanism like:

    % Constants - call f’n here to prevent overwriting
    PLANCK;
    PI_OVER_TWO;

    The problem is, this seems to be a very clunky way to provide constant-like functionality without having to add them to the Matlab scripting language. Why not just figure out how to support constants, and then support them?

  8. StephenLL replied on :

    Check out the new class system in R2008a for support for constants.

Leave a Reply


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Ulla Vainio: That error bar width adjustment was extremely useful and I would never have figured it out myself....
  • Peter Perkins: Jessee, there is a property that you can use to tag variables with units. For example, >> load...
  • Jessee: I could potentially see myself using dataset for casually looking at data, but from an application standpoint...
  • Loren: Oktay- It very much depends on the details of the calculations you are doing. Vectorization can sometimes...
  • Oktay: Hello, Is there any significant difference between using: - Vectorization inside a subfunction - Benefiting...
  • Loren: Clare- Yes, sum can sum a double vector: x = [.3 .4 pi/3] y = sum(x) x = 0.3 0.4 1.0472 y = 1.7472 You must...
  • Clare J: R2007a - Student Version When I use sum to sum a vector of type double I get this error message: ???...
  • Sarah Zaranek: Hi Jacob, Sorry about the slow response. You are correct that the code would be slower without the...
  • Navaneethan Santhanam: Thanks a lot, Loren! That worked perfectly.
  • Mike N: Should it be OK to use “persistent 221; variables in a deployed application? What if I have two...

These postings are the author's and don't necessarily represent the opinions of The MathWorks.

Related Topics