Skip to content

MATLAB - Categorical Arrays

A categorical array is a specialized MATLAB data type designed to efficiently store and manage data that comes from a finite set of discrete categories. Think of data like ‘gender’ (Male, Female, Non-binary), ‘size’ (Small, Medium, Large), or survey responses (Agree, Neutral, Disagree).

While you could use string arrays or cell arrays of characters for this, categorical arrays offer significant advantages in terms of memory usage, performance, and analytical capabilities.

  • Memory Efficiency: Instead of storing long, repetitive strings like “United States of America” thousands of times, a categorical array stores each unique string once and uses lightweight integer codes to represent the data. This dramatically reduces memory usage for large datasets.
  • Performance Boost: Comparing integers is much faster than comparing strings. Operations like sorting, grouping, and comparing are significantly faster on categorical arrays.
  • Controlled Vocabulary: Categorical arrays enforce a fixed set of categories. This prevents typos (e.g., ‘red’, ‘Red’, ‘redd’) from being treated as distinct categories, ensuring data integrity.
  • Enhanced Analytics & Plotting: Many MATLAB functions for statistics and plotting are specifically designed to work with categorical data, automatically creating grouped summaries and labeled plots.

You can create categorical arrays from existing data using the categorical() function or by binning continuous data with the discretize() function.

The categorical() function converts a string array, cell array, or numeric array into a categorical array.

%% Example 1: From a string array
colorData = ["Red", "Blue", "Green", "Red", "Green"];
% Convert to a categorical array
primaryColors = categorical(colorData);
disp(primaryColors);
% To see the unique, sorted categories
disp(categories(primaryColors));
% --- Output ---
% 1x5 categorical array
%
% Red Blue Green Red Green
%
% 3x1 cell array
% {'Blue' }
% {'Green'}
% {'Red' }
%% Example 2: From numeric data with specified labels
% Imagine a survey where 1=Low, 2=Medium, 3=High
responseData = [1 3 2; 2 1 3; 3 1 2];
valueSet = [1, 2, 3];
categoryNames = {"Low", "Medium", "High"};
% The mapping is based on order: valueSet(i) maps to categoryNames{i}
% So, 1 -> "Low", 2 -> "Medium", 3 -> "High"
C = categorical(responseData, valueSet, categoryNames);
disp(C);
% --- Output ---
% 3x3 categorical array
%
% Low High Medium
% Medium Low High
% High Low Medium
%% Example 3: Creating an Ordinal Categorical Array
% Ordinal means the categories have a natural order (e.g., Small < Medium < Large)
sizeData = {"Medium"; "Small"; "Large"; "Medium"};
% Define the categories in their correct order
sizeOrder = {"Small", "Medium", "Large"};
% Create the categorical array and specify it's ordinal
B = categorical(sizeData, sizeOrder, 'Ordinal', true);
disp(B);
% Now you can perform logical comparisons based on the order
% Find all sizes greater than Medium
isLargerThanMedium = B > "Medium";
disp(isLargerThanMedium);
% --- Output ---
% 4x1 categorical array
%
% Medium
% Small
% Large
% Medium
%
% 4x1 logical array
%
% 0
% 0
% 1
% 0

discretize is perfect for converting continuous numeric data into discrete bins.

%% Example: Binning student scores into grade categories
scores = [68, 75, 82, 90, 55, 78, 92, 60, 88, 72];
% Define the edges of the bins: (0, 60], (60, 80], (80, 100]
binEdges = [0, 60, 80, 100];
binNames = {"Fail", "Pass", "Merit"};
% Discretize the scores into named categories
gradeCategories = discretize(scores, binEdges, 'Categorical', binNames);
disp(gradeCategories);
% --- Output ---
% 1x10 categorical array
%
% Pass Pass Merit Merit Fail Pass Merit Fail Merit Pass

One of the most powerful uses of categorical arrays is for performing grouped calculations with functions like groupcounts and groupsummary.

%% Example: Analyze sales data by product category
% Create a table of sales data
salesTbl = table(
categorical(["Laptop";"Monitor";"Laptop";"Keyboard";"Monitor";"Laptop"]),
[1200; 350; 1350; 75; 400; 1150],
'VariableNames', {'ProductType', 'SalePrice'}
);
disp('Original Sales Data:');
disp(salesTbl);
% Use groupcounts to find the number of sales for each product type
productCounts = groupcounts(salesTbl, 'ProductType');
disp('Sales Counts per Product:');
disp(productCounts);
% Use groupsummary to find the mean sale price for each product type
productMeanPrice = groupsummary(salesTbl, 'ProductType', 'mean', 'SalePrice');
disp('Mean Price per Product:');
disp(productMeanPrice);
% --- Output ---
% Original Sales Data:
% ProductType SalePrice
% ___________ _________
%
% Laptop 1200
% Monitor 350
% Laptop 1350
% Keyboard 75
% Monitor 400
% Laptop 1150
%
% Sales Counts per Product:
% ProductType GroupCount
% ___________ __________
%
% Keyboard 1
% Laptop 3
% Monitor 2
%
% Mean Price per Product:
% ProductType GroupCount mean_SalePrice
% ___________ __________ ______________
%
% Keyboard 1 75
% Laptop 3 1233.3
% Monitor 2 375