Wednesday, December 24, 2008

Constants in MATLAB

MATLAB scripts often include a number that is needed in many calculations and whose value never changes. Examples of this are acceleration due to gravity and the conversion factor of feet to meters. In C/C++ I'd do something like this:

#define SECONDS_IN_ONE_MINUTE 60;

Unfortunately, there is no '#define' in MATLAB, so I have to use a work around. I'll refer interested readers to a nice blog post by Loren Shure. Loren suggests making a seperate .m file to contain my constant definitions. Such as:

% constants.m

function x = Seconds_In_One_Minute()

x = 60;

Since MATLAB has some strange syntax (to C/C++ programmers), I can just use the name of the function as though it is a variable. Such as:

Hours = Seconds / Seconds_In_One_Minute;

I haven't had any problems using this technique, but there are some obvious flaws. Most importantly, the value of the constant can be changed anywhere in the program. It'd be nice if MATLAB included a type or keyword so a variable could only be assigned a value once. Also, simply using a one-line '#define' statement is much more elegant than have to make a separate file for constants.