Domanda

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

Enum:

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

Usage:

directions(Enumeration1.Left) = 7;

To me this should be the same as

directions(1) = 7;

but I get 'Subscript indices must either be real positive integers or logicals'.

alternatively when I use a containers.Map object, all examples I see have keys as strings. When I use an enumeration I get 'Specified key type 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 an enumerated value?

È stato utile?

Soluzione

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

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

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

b = uint32(a);

So the following should work:

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

Interestingly - when I use Matlab 2012a, I can actually use the syntax you have above, and Matlab doesn't complain.

Altri suggerimenti

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

Note that against everything else in MATLAB, subsindex must return zero-based indices.

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 the defining the subsindex method, classes that inherit from builtin type should work as indices as usual (at least it worked this way in my R2013a version).


If you want to work with containers.Map, you must explicitly cast the enumeration as uint32. I think the containers.Map/subsref method does not use isa to test the type of the indexing term, 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. 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top