Search code examples
matlabconstantsmatlab-class

Constants in MATLAB


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


Solution

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