gpt4 book ai didi

Matlab:指定的值类型与该容器的预期类型不匹配

转载 作者:行者123 更新时间:2023-12-02 06:45:21 24 4
gpt4 key购买 nike

我在使用 matlab 的容器.Map 时遇到问题。

这是我的问题的示例:

当我尝试使用定义为的键元胞数组构建 myClass 实例数组的映射时:

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);

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

我收到此错误:

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

但是 matlab 文档说:

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.

我还尝试指定类类型,但它也引发了错误:

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

所以我不明白...如果containers.Map适用于任何类,为什么不适用于myClass?

最佳答案

如果你这样做

help containers.Map

你会看到一个部分,上面写着

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.

您可以使用:

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

但是,您可能想要的行为是:

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

当您输入正确的 key 时,这将为您提供一个 myClass 类型的对象。这很可能是因为 containers.Map 需要自定义对象的元胞数组而不是对象数组。

您的代码看起来会更清晰,如下所示:

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:指定的值类型与该容器的预期类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17685364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com