我正在开发一个MatLab程序,我将双打映射到双打。地图工作正常。但是,当我从这样的地图中检索值时:
number1 = map(i); % i is a double
它给我一个错误:
Specified key type does not match the type expected for this container.
为什么它会给我这个错误?请注意,这不是重复,因为我遇到的所有其他问题都在谈论将信息放入Map
,而不是将其取出。网络上的问题也是如此,我还没有看到一个处理地图中的retreiving值。我的完整代码如下:
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
答案 0 :(得分:3)
map的默认密钥类型是字符串。如果你想使用double,你需要明确定义它,例如
map = containers.Map('KeyType', 'double', 'ValueType', 'any');
您可以按如下方式添加值:
map(3) = 4;
map(5) = 14;
map(15) = {'fdfd', 'gfgfg'};
获取密钥:
map.keys
ans =
[3] [5] [15]
一些快速测试密钥是否可以是双精度数组:
>> 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.
答案 1 :(得分:1)
不确定你要做什么因为C和G都相等所以D和H都是相等的,所以地图会将值映射到它自己。我想你正试图建立一个数字所有权力的地图。尝试下面的代码。
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);
你可以制作任何你想要的地图,包括双打......例如
map = containers.Map({1.5,2.1,3},{[1,2,3],3,[5,2]});
map(1.5)
map(2.1)
map(3)