Not able to append to an empty container map

I've been trying to write a function that divides a matrix based on its 'class value' . For example, if we have an matrix like -
1 2 1
3 4 0
1 3 1
6 7 2
6 7 0
6 7 1
we should get
(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
I've written this so far using a container map, since I want to closely represent a Python dictionary.
I want to create a new key-value pair in the map if the class in focus is not already a key of the map. And if it already exists as a key, I want to append it to the existing value (which is a matrix) for that key.
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;
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
Using the same matrix used as an example as the input 'dataset', I get an error on the first iteration of the for loop, on trying to run the line
separated(class_var) = vector;
The error I get is
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;
I can't figure how to fix the data type issue in this!

 채택된 답변

Walter Roberson
Walter Roberson 2019년 7월 15일

2 개 추천

https://www.mathworks.com/help/matlab/ref/containers.map.html
The default key type is char, so use the keytype valuetype options to change the default.

댓글 수: 1

Sanjan Das
Sanjan Das 2019년 7월 15일
Yes, changed the type to 'any', and works now! Thanks.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

제품

질문:

2019년 7월 15일

댓글:

2019년 7월 15일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by