我一直在尝试编写一个函数,该函数根据其“类值”划分矩阵。例如,如果我们说向量输入的“类”是最后一列中的值,我想拆分一个矩阵,如
[1 2 1; ...
3 4 0; ...
1 3 1; ...
6 7 2; ...
6 7 0; ...
6 7 1]
as(基于最后一列的值)
(Class 1)
[1 2 1; ...
1 3 1; ...
6 7 1]
and
(Class 0)
[3 4 0; ...
6 7 0]
and
(Class 2)
[6 7 2]
我希望格式尽可能接近 Python 字典,因此我选择了容器映射。但是我对容器映射的键类型有一些问题。
这是我写的函数。
function [separated] = separateByClass(dataset)
% assume the class variable is the last column of the dataset
% We return a container map mapping the unique class variables to the
% row instances from the dataset
separated = containers.Map; % setting up the container map
for i=1:size(dataset, 1)
vector = dataset(i, :);
class_var = vector(end);
if isKey(separated, class_var)== 0
separated(class_var) = vector;
else
separated(class_var) = [separated(class_var); vector];
end
end
end
separated(class_var) = vector;在循环的第一次迭代期间,我在线路上收到一条错误消息。
Error using containers.Map/subsasgn
Specified key type does not match the type expected for this container.
Error in separateByClass (line 12)
separated(class_var) = vector;
如果问题是我要添加到空容器映射中,那么我不知道,所以键类型不匹配?