First of all, having lots of short files is the normal situation in MATLAB. Working around that is possible but oftentimes futile.
Traditionally in MATLAB, constant values are defined as a function. For example, pi
is a function. It looks something like this:
function v = pi
v = 3.14159
By making the constant into a function, it is available from everywhere without first running code to define those constants.
An enumeration is nothing more than a series of constants. The same can be accomplished with a struct:
exampleEnumType = struct('zero',0, 'one',1, 'two',2);
Since fairly recently (R2019b), MATLAB allows dot indexing into the output of a function call, but you do need to use empty parenthesis in the function call. Thus, we can declare the above struct the same way we did with constants:
function v = exampleEnumType
v = struct('zero',0, 'one',1, 'two',2);
This allows to do exampleEnumType().zero
(almost) like with the enum or with a struct variable.
So how do we extend this to defining multiple of these in a single file? If a common prefix is no problem, we can define a class with static member functions, each one declaring a constant:
classdef constants
methods(Static)
function v = pi
v = 3.14159
end
function v = exampleEnumType
v = struct('zero',0, 'one',1, 'two',2);
end
end
end
We now have constants.pi
and constants.exampleEnumType().zero
.
Alternatively, create a single function that returns a more complex struct as follows:
function v = constants
v.pi = 3.14159;
v.exampleEnumType = struct('zero',0, 'one',1, 'two',2);
This allows us to do constants().exampleEnumType.zero
.
Note that the above will not work in the same way for MATLAB releases prior to R2019b. For older versions of MATLAB, the last method (a function constants
) would be the best approach. The user would just need to do constants = constants;
at the top of any function needing to use the constants. This shadows the function with a variable of the same name, so that constants.exampleEnumType.zero
works as expected.