Not able to append to an empty container map

11 views (last 30 days)
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!

Accepted Answer

Walter Roberson
Walter Roberson on 15 Jul 2019
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.

More Answers (0)

Categories

Find more on Dictionaries in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!