Pergunta

I'm developing a MatLab program where I map doubles to doubles. The map works fine. However, when I go to retrieve a value from a map like this:

number1 = map(i); % i is a double

It gives me an error that:

Specified key type does not match the type expected for this container.

Why is it giving me this error? Please note, this is not a duplicate as all other questions I've come across are talking about putting information into a Map, not taking it out. This has also been the case for questions across the web, I haven't seen one dealing with retreiving values from a map. My full code is below:

C = [];
D = [];
E = [];
F = [];
G = [];
H = [];

numbers = 10;
powers = 10;

format longG

for i = 1:numbers 
    for j = 3:powers
        C = [C;i^j]; 
        G = [G;i^j];
    end  
    C = transpose(C);
    D = [D;C];  
    C = [];
    G = transpose(G);
    H = [H;G];  
    G = [];
end

    map = containers.Map(D,H)

[~,b] = unique(D(:,1)); % indices to unique values in first column of D
D(b,:);                  % values at these rows

for i = D
    number1 = map(i);
    for a = D
        number2 = map(a);
        if gcd(number1,number2) == 1
        E = [E;i+a];
        end
    end
    E = transpose(E);
    F = [F;E];  
    E = [];
end
Foi útil?

Solução

The default key type for map is string. If you want to use double you need to explicitly define it, e.g.

map = containers.Map('KeyType', 'double', 'ValueType', 'any');    

You can add values as follows:

map(3) = 4;
map(5) = 14;
map(15) = {'fdfd', 'gfgfg'};

Getting keys:

map.keys

ans = 

     [3]    [5]    [15]

Some quick test if key can be an array of doubles:

>> keyTest = [1,2,3]';
>> class(keyTest)

ans =

double

>> map = containers.Map('KeyType', 'double', 'ValueType', 'any'); 
>> map(keyTest) = 4
Error using containers.Map/subsasgn
Specified key type does not match the type expected for this container.

Outras dicas

Not sure what you are trying to do because both C and G are equal so D and H will be equal, so the map will map a value to itself. I think you are trying to build a map of all the powers of a number. Try to below code.

numbers = 1:10;
powers = 3:10;

my_num_matrix = repmat(numbers', 1, length(powers));
my_pow_matrix = repmat(powers, length(numbers), 1);

my_result_matrix = my_num_matrix .^ my_pow_matrix;

my_map_values = mat2cell(my_result_matrix, ones(1, length(numbers)), length(powers));

power_map = containers.Map(numbers, my_map_values);

You can make map of whatever you want, including doubles... for instance

map = containers.Map({1.5,2.1,3},{[1,2,3],3,[5,2]});
map(1.5)
map(2.1)
map(3)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top