Main Content

addcats

Add categories to categorical array

Description

B = addcats(A,newcats) adds categories to a categorical array. By default, addcats adds the new categories to the end of the set of categories, as shown by the output of categories(A). It does not add new elements. The output categorical array B does not contain elements that belong to any of the new categories until you assign such elements to B.

If A is an ordinal categorical array, you must specify the Before or After name-value argument.

example

B = addcats(A,newcats,Before=catname) adds categories before the specified category.

example

B = addcats(A,newcats,After=catname) adds categories after the specified category.

Examples

collapse all

Create a categorical array.

A = categorical(["red" "blue" "red" "blue" "red" "blue"])
A = 1×6 categorical
     red      blue      red      blue      red      blue 

Display the categories of the array.

categories(A)
ans = 2×1 cell
    {'blue'}
    {'red' }

Add the categories, green and black, to the end of the set of categories. The new array has the same elements but it has more categories.

B = addcats(A,["green" "black"])
B = 1×6 categorical
     red      blue      red      blue      red      blue 

categories(B)
ans = 4×1 cell
    {'blue' }
    {'red'  }
    {'green'}
    {'black'}

Create an ordinal categorical array.

A = categorical(["medium" "large"; "small" "xlarge"; "large" "medium"], ...
                ["small" "medium" "large" "xlarge"], ...
                Ordinal=true)
A = 3×2 categorical
     medium      large  
     small       xlarge 
     large       medium 

Display the categories. Because A is ordinal, the categories have the mathematical ordering small < medium < large < xlarge.

categories(A)
ans = 4×1 cell
    {'small' }
    {'medium'}
    {'large' }
    {'xlarge'}

Add the category xsmall before small. Then display the categories of the new array. Its categories have the mathematical ordering xsmall < small < medium < large < xlarge.

B = addcats(A,"xsmall",Before="small");
categories(B)
ans = 5×1 cell
    {'xsmall'}
    {'small' }
    {'medium'}
    {'large' }
    {'xlarge'}

Input Arguments

collapse all

Input array, specified as a categorical array.

New categories, specified as a string array, character vector, or cell array of character vectors.

Name of a category, specified as a string scalar or character vector.

Extended Capabilities

expand all

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Version History

Introduced in R2013b