Matlab: Specified value type does not match the ty

2019-01-28 22:57发布

问题:

I am experiencing problems to use the containers.Map of matlab.

Here an example of my issue:

When I try to build the map of an array of myClass instance with a cellarray of keys defined as :

valueSet = myClass.empty(4,0);
keySet = cell(1,4);

for i=1:4
   valueSet(i) = myClass();
   keySet{i} = valueSet(i).name;
end
map = containers.Map(keySet, valueSet);

with

classdef myClass < handle
    properties
        name;
    end

    methods
        function self = myClass()
            self.name = randstr(10);
        end

        function output = randstr(n)
            symbols = ['a':'z' 'A':'Z' '0':'9'];
            nums = randi(numel(symbols),[1 n]);
            output = symbols (nums);
        end
    end
end

I get this error:

Error using containers.Map
Specified value type does not match the type expected for this container.

However the matlab documentation says :

mapObj = containers.Map(keySet,valueSet) constructs a Map that contains one or more values and a unique key for each value.

keySet 1-by-n array that specifies n unique keys for the map. If n > 1 and the keys are strings, keySet must be a cell array.

valueSet : 1-by-n array of any class that specifies n values for the map. The number of values in valueSet must equal the number of keys in keySet.

I also tried to specified the class type but it raised also an error:

containers.Map('KeyType','char', 'ValueType','myClass')
Error using containers.Map
Unsupported ValueType 'myClass' specified.  See documentation for valid value types.

So I don't understand... if containers.Map is working for any class, why is not working for myClass ?

回答1:

If you do

help containers.Map

you get a section which says

Valid values for vType are the strings: 'char', 'double', 'single', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'logical', or 'any'. The order of the key type and value type arguments is not important, but both must be provided.

You could use:

containers.Map('KeyType','char', 'ValueType','any')

However, the behaviour that you probably want is:

myMap = containers.Map(keySet, num2cell(valueSet))

That will give you one an object of type myClass when you put in the correct key. This is most likely because containers.Map is expecting a cell array of custom objects rather than an object array.

Your code would look clearer like this:

valueSet = cell(1,4);
keySet = cell(1,4);

for i=1:4
   valueSet{i} = myClass();
   keySet{i} = valueSet{i}.name;
end

map = containers.Map(keySet, valueSet);


标签: matlab map