categorical

Array of values from a fixed set of categories, stored as labels.

Category: Language Fundamentals > Data Types

Syntax

C = categorical(A)

Creates categories from the unique values of A, sorted.

C = categorical(A, valueset)

Uses the listed values as the categories, in that order.

C = categorical(A, valueset, catnames)

Also renames the categories.

C = categorical(___, 'Ordinal', true)

Makes the categories ordered so they can be compared with < and >.

Description

A categorical array stores a small integer code per element plus a list of category names, so repeated labels use little memory and comparisons are fast. Values can be tested with == against a category name, and categories, countcats and summary describe the contents.

Elements that do not belong to any category are <undefined>. When 'Ordinal' is true, the order of valueset defines the ranking.

Input arguments

A
Numeric, logical, string, char cell array or categorical data.
valueset
Values to treat as categories; values of A not in the list become undefined.
catnames
Names for the categories, one per value in valueset.

Output arguments

C
categorical array of the same size as A.

Example

Labels and category list

c = categorical({'lo','hi','lo','mid'}, {'lo','mid','hi'}, 'Ordinal', true)
categories(c)
countcats(c)
Output
c = 1×4 categorical array

     lo      hi      lo      mid 
ans = 3×1 cell

    {'lo' }
    {'mid'}
    {'hi' }
ans = 1×3

     2     1     1

See also

categories countcats summary discretize unique