Are there enumerated types in MATLAB? If not, what are the alternatives?
相关问题
- Extract matrix elements using a vector of column i
- What is the fastest for Map keys: Enum.valueOf(~)
- How do you get R's null and residual deviance
- Switch String with Enum variables
- How to display an image represented by three matri
相关文章
- Enum with associated value conforming to CaseItera
- Why do I have to cast enums to int in C#?
- How do I append metadata to an image in Matlab?
- Why doesn't reflections.getSubTypesOf(Object.c
- How can I get enum possible values in a MySQL data
- How can I write-protect the Matlab language?
- Bind a char to an enum type
- ClassLoad an Enum type
Starting from R2010b, MATLAB supports enumerations.
Example from the documentation:
After trying out the other suggestions on this page, I landed on Andrew's fully object-oriented approach. Very nice - thanks Andrew.
In case anyone is interested, however, I made (what I think are) some improvements. In particular, I removed the need to double-specify the name of the enum object. The names are now derived using reflection and the metaclass system. Further, the eq() and ismember() functions were re-written to give back properly-shaped return values for matrices of enum objects. And finally, the check_type_safety() function was modified to make it compatible with package directories (e.g. namespaces).
Seems to work nicely, but let me know what you think:
Thanks, Mason
You can get some of the functionality with new-style MATLAB classes:
This isn't really a type, but since MATLAB is loosely typed, if you use integers, you can do things that approximate it:
In this case, MATLAB "enums" are close to C-style enums - substitute syntax for integers.
With the careful use of static methods, you can even make MATLAB enums approach Ada's in sophistication, but unfortunately with clumsier syntax.
If you have access to the Statistics Toolbox, you might consider using a categorical object.
If you want to do something similar to what Marc suggested, you could simply make a structure to represent your enumerated types instead of a whole new class:
One benefit is that you can easily access structures in two different ways. You can specify a field directly using the field name:
or you can use dynamic field names if you have the field name in a string:
In truth, there are a few benefits to doing what Marc suggested and creating a whole new class to represent an "enum" object:
However, if you don't need that sort of complexity and just need to do something quick, a structure is likely the easiest and most straight-forward implementation. It will also work with older versions of MATLAB that don't use the newest OOP framework.
You could also use Java enum classes from your Matlab code. Define them in Java and put them on your Matlab's javaclasspath.
You can reference them by name in M-code.
It won't catch comparisons to other types, though. And comparison to string has an odd return size.