Categorical Data
Many columns in a data set hold one of a small, fixed set of values: a colour, a department, a T-shirt size, a test result of "pass" or "fail". Statisticians call these categorical variables. Storing them as text works, but it repeats the same strings thousands of times and makes it easy to mistype a value. MATLAB's categorical type (R2013b and later) stores each value as a small integer code plus one shared list of category names.
Note: Octave 11 has no
categoricalclass. This lesson explains it with MATLAB output, then shows the idea underneath, a vector of integer codes plus a list of level names, which you can use in any MATLAB or Octave code.
Creating a categorical array
% MATLAB only
c = categorical({'red', 'blue', 'red', 'green', 'blue', 'red'})
categories(c)
countcats(c)MATLAB output:
c =
1×6 categorical array
red blue red green blue red
ans =
3×1 cell array
{'blue' }
{'green'}
{'red' }
ans =
2 1 3The categories are the unique values, sorted alphabetically by default. countcats counts each one, summary(c) prints names and counts together, and c == 'red' compares against a category name without any strcmp. Charts understand categorical data too: histogram(c) or bar(categories(c), countcats(c)) draws one bar per category.
Codes and levels: how it works
Underneath, a categorical array is just two things: an integer code for every element and a list of level names. unique builds exactly that from text. Its first output is the list of levels and its third output (code here) is the code of every element:
colors = {'red', 'blue', 'red', 'green', 'blue', 'red'};
[levels, ~, code] = unique(colors);
code = code(:)';
disp(levels)
disp(code)
fprintf('element 4 is level %d: %s\n', code(4), levels{code(4)});
back = levels(code);
fprintf('decoded: %s\n', strjoin(back, ' '));{
[1,1] = blue
[1,2] = green
[1,3] = red
}
3 1 3 2 1 3
element 4 is level 2: green
decoded: red blue red green blue red
levels(code) decodes the whole array in one indexing operation. Everything else categorical arrays do follows from this representation.
Counting categories
accumarray(code, 1) adds a 1 to the bin of each code, which is exactly countcats. Give it the number of levels as the size so that categories with no elements still get a count of 0:
colors = {'red', 'blue', 'red', 'green', 'blue', 'red'};
levels = {'blue', 'green', 'red', 'yellow'};
[~, code] = ismember(colors, levels);
counts = accumarray(code(:), 1, [numel(levels) 1])';
for k = 1:numel(levels)
fprintf('%-7s %d %s\n', levels{k}, counts(k), repmat('*', 1, counts(k)));
end
[~, most] = max(counts);
fprintf('most common: %s\n', levels{most});blue 2 **
green 1 *
red 3 ***
yellow 0
most common: red
Here the levels are a fixed list chosen in advance (including yellow, which doesn't occur), and ismember returns each element's position in that list. In MATLAB, categorical(colors, levels) does the same thing.
Order of categories
unique sorts levels alphabetically. Use unique(x, 'stable') to keep them in the order they first appear, or pass your own list to ismember as above:
answers = {'yes', 'no', 'maybe', 'yes', 'no', 'yes'};
alpha = unique(answers)
[stable, ~, code] = unique(answers, 'stable');
disp(stable)
disp(code(:)')alpha =
{
[1,1] = maybe
[1,2] = no
[1,3] = yes
}
{
[1,1] = yes
[1,2] = no
[1,3] = maybe
}
1 2 3 1 2 1
Ordinal categories
Some categories have a natural order: sizes S < M < L < XL, ratings low < medium < high. MATLAB's ordinal categorical arrays support <, >, sort, min and max according to that order:
% MATLAB only
sizes = categorical({'M', 'S', 'L', 'M', 'XL', 'S'}, {'S', 'M', 'L', 'XL'}, 'Ordinal', true);
sizes(sizes >= 'L')
max(sizes)
sort(sizes)MATLAB output:
ans =
1×2 categorical array
L XL
ans =
categorical
XL
ans =
1×6 categorical array
S S M M L XL With codes this is natural: if the level list is in order, the code itself is the rank, so comparisons and sorting are numeric operations:
order = {'S', 'M', 'L', 'XL'};
sizes = {'M', 'S', 'L', 'M', 'XL', 'S'};
[~, rank] = ismember(sizes, order);
disp(rank)
large = sizes(rank >= 3)
fprintf('largest: %s\n', order{max(rank)});
[~, k] = sort(rank);
fprintf('sorted: %s\n', strjoin(sizes(k), ' ')); 2 1 3 2 4 1
large =
{
[1,1] = L
[1,2] = XL
}
largest: XL
sorted: S S M M L XL
Sorting the text directly would give L M M S S XL, alphabetical but meaningless for sizes.
Undefined values
A value that isn't one of the categories becomes <undefined> in MATLAB, the categorical version of NaN. isundefined detects it:
% MATLAB only
c = categorical({'low', 'high', 'hgih', 'low'}, {'low', 'medium', 'high'})
isundefined(c)MATLAB output:
c =
1×4 categorical array
low high <undefined> low
ans =
1×4 logical array
0 0 1 0With codes, a value that ismember can't find gets code 0, which makes typos easy to report:
levels = {'low', 'medium', 'high'};
raw = {'low', 'high', 'hgih', 'low', 'Medium'};
[ok, code] = ismember(raw, levels);
disp(code)
bad = raw(~ok);
fprintf('unknown values: %s\n', strjoin(bad, ', '));
[ok2, code2] = ismember(lower(raw), levels);
fprintf('after lower(): %d unknown\n', sum(~ok2)); 1 3 0 1 0
unknown values: hgih, Medium
after lower(): 1 unknown
Cleaning with lower (or strtrim) before encoding fixes the case problem; the misspelling hgih still needs a human decision.
Renaming and merging categories
MATLAB has a family of functions for editing the category list: renamecats, mergecats, addcats, removecats and reordercats.
% MATLAB only
c = categorical({'cat', 'dog', 'hamster', 'dog', 'rabbit'});
c = mergecats(c, {'hamster', 'rabbit'}, 'small pet');
categories(c)'
countcats(c)'MATLAB output:
ans =
1×3 cell array
{'cat'} {'dog'} {'small pet'}
ans =
1 2 2With codes, renaming only changes the level list, without touching the data, and merging maps old codes to new ones with a lookup vector:
levels = {'cat', 'dog', 'hamster', 'rabbit'};
pets = {'cat', 'dog', 'hamster', 'dog', 'rabbit'};
[~, code] = ismember(pets, levels);
levels{1} = 'kitten';
fprintf('renamed: %s\n', strjoin(levels(code), ' '));
newLevels = {'kitten', 'dog', 'small pet'};
map = [1 2 3 3];
code2 = map(code);
disp(code2)
counts = accumarray(code2(:), 1)';
for k = 1:numel(newLevels)
fprintf('%-10s %d\n', newLevels{k}, counts(k));
endrenamed: kitten dog hamster dog rabbit
1 2 3 2 3
kitten 1
dog 2
small pet 2
map(code) says "old level 3 (hamster) and old level 4 (rabbit) both become new level 3".
Statistics per category
The codes are also perfect group numbers for accumarray, which computes one result per category, as in the group summaries of the Tables lesson:
region = {'north', 'south', 'north', 'east', 'south', 'north'};
sales = [120 80 150 60 95 130];
[names, ~, g] = unique(region);
total = accumarray(g(:), sales(:));
avg = accumarray(g(:), sales(:), [], @mean);
for k = 1:numel(names)
fprintf('%-6s total %4d mean %6.1f\n', names{k}, total(k), avg(k));
endeast total 60 mean 60.0
north total 400 mean 133.3
south total 175 mean 87.5
Why use categories at all?
| Benefit | With MATLAB categorical |
With codes + levels |
|---|---|---|
| Less memory | Automatic (1 byte per element for up to 255 categories) | Store codes as uint8/uint16 |
| Fixed, valid set of values | Invalid values become <undefined> |
ismember returns 0 |
| Meaningful order | 'Ordinal', true |
Put the levels in order; code = rank |
| Counting and grouping | countcats, groupsummary |
accumarray(code, 1) |
| Readable display | Automatic | Decode with levels(code) |
For a column with a million rows but only five distinct values, codes take a fraction of the memory of a cell array of text and make comparisons much faster, because comparing small integers is cheaper than comparing strings.
Learn more: Sets & unique, Tables and, for the same concept in Python, pandas categoricals.
Test yourself
Which call counts how often each category occurs, given integer codes code (1 to n)?
accumarray(code(:), 1)sum(code)unique(code)sort(code)
For ordinal sizes with levels {'S','M','L','XL'}, why is comparing the codes enough to compare sizes?
- Because the levels are listed in order, so each code is the rank
- Because codes are sorted alphabetically
- Because ismember returns logical values
- It isn't; you must compare the text
In MATLAB, what does a value outside the category list become in categorical(data, cats)?
<undefined>NaN- An empty string
- The first category