Can I use an enumeration as an index for a vector or MATLAB map?

I am looking to use an enumeration to access elements of an array or dictionary, but no luck.

Enum:

classdef Enumeration1 < uint32 enumeration Left (1); Right (2); Neither (3); end end 

Using:

 directions(Enumeration1.Left) = 7; 

For me it should be the same as

 directions(1) = 7; 

but I get "Index indices must be either natural integers or booleans."

alternatively, when I use the containers.Map object, all the examples that I see have keys as strings. When I use the enumeration, I get "The type of the specified key does not match the type expected for this container." I can see from help containers.Map that uint32 is an acceptable key type.

How can I effectively index objects using a listed value?

+4
source share
2 answers

If you look at the example provided at http://www.mathworks.com/help/matlab/matlab_oop/enumerations.html , you will see that the value of Enumeration1.Left not a value of 1 , but an object instead. You can confirm this by examining the returned object:

 a = Enumeration1.Left; whos a display(a) 

This shows that a is an object of class Enumeration1 with a size of 108 bytes and a value of Left . Converting Left to 1 is done using

 b = uint32(a); 

So the following should work:

 directions(uint32(Enumeration1.Left)) = 7; 

Interestingly, when I use Matlab 2012a, I can use the syntax you have above, and Matlab does not complain.

+3
source

In general, to use objects as indexes , define a subsindex for your class.

Note that against everything else in MATLAB, subsindex should return indexes with a null value.

 classdef E < uint32 enumeration Left (1); Right (2); Neither (3); end methods function ind = subsindex(obj) ind = uint32(obj) - 1; end end end 

Example:

 >> x = 1:10; >> x(E.Right) ans = 2 

Note that even without defining a subsindex method subsindex classes that inherit from the built-in type should work as indexes as usual (at least it worked that way in my version of R2013a).


If you want to work with container.Map, you must explicitly list the enum as uint32 . I think the containers.Map/subsref method does not use isa to check the type of indexing, instead use something like strcmp(class(obj),'..') , which explains the error message:

 Error using containers.Map/subsref Specified key type does not match the type expected for this container. 
+2
source

Source: https://habr.com/ru/post/1498434/


All Articles