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 planck1 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



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.
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.
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;
—
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.
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.
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.
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?
Check out the new class system in R2008a for support for constants.
I wanted to define a large number of constants in a GUI that I wrote and found that I could make use of anonymous functions as a method of ‘protecting’ them from accidental change.
The initialization code in my GUI follows the following sequence:
c = CreateConstants(); % Returns a structure, c, of ‘constants’
h = CreateGuiObjects(c); % Returns a structure, h, of handles to GUI objects.
AssignGuiCallbacks(h,c); % Assigns callbacks to objects
As long as the assignments made in AssignGuiCallbacks use anonymous function calls, the argument c is fixed at the time the assignment is made (refer to Matlab help on the topic). An example of an assignment might be:
set(h.tmrMain,’TimerFcn’,{@tmrMain_TimerFcn,h,c});
Whenever the TimerFcn event is subsequently triggered, tmrMain_TimerFcn will always use the value of c that was defined at the time the anonymous function call was defined.
I have found this technique to be very useful in this application as all functions are callbacks, or called as a sub-routine from a function that is a callback.
This method is still not bulletproof; there is nothing to prevent one from changing c from withing a function, although changes will not persist between calls.
I also find that using a structure such as this mitigates the risk of changes as a) it is obvious that anything that is part of the structure is not meant to be changed and b) a short name like ‘c’ reserves plenty of room for descriptive field names. I prefer to name globals in ALL CAPS in order to make the distinction between the two variable types.
Having said all this, I _would_ like the ability to define true constants in Matlab. My concern about the ‘function’ method outlined by Loren above, is the potential performance hit encountered if many constants are used in time-sensitive calculations. Is this a reasonable concern?
Gene
I know this thread is old, but I would like to add my motivation for constants. I’m writing m-File S-Functions and referencing Dwork arrays would be much clearer if there existed “c” style header files. I’m otherwise left with either creating a function (as described above) to define each index into the Dwork array, or using a verbose class/property technique (Constants.SFunc.WFM to demystify ‘1′). A single function that returned a structure seems the best compromise, but I would prefer that Mathworks publish a coding style recommendation that could be more uniformly adopted (ideally with a terse format).
Thanks!