defined as character vectors, which can be costly to store and manipulate in a cell array
of character vectors or char array. Categorical arrays store only one copy of each
category name, often reducing the amount of memory required to store the array.
Create a sample cell array of character vectors.
state = [repmat({'MA'},25,1);repmat({'NY'},25,1);...
repmat({'CA'},50,1);...
repmat({'MA'},25,1);repmat({'NY'},25,1)];
Display information about the variable state.
whos state
Name Size Bytes Class Attributes
state 150x1 17400 cell
The variable state is a cell array of character vectors requiring 17,400 bytes of memory.
Convert state to a categorical array.
state = categorical(state);
Display the discrete categories in the variable state.
categories(state)
ans = 3x1 cell array
{'CA'}
{'MA'}
{'NY'}
state contains 150 elements, but only three distinct categories.
Display information about the variable state.
whos state
Name Size Bytes Class Attributes
state 150x1 500 categorical
There is a significant reduction in the memory required to store the variable.
8 Categorical Arrays