Main Content

renamecats

Rename categories in categorical array

Description

B = renamecats(A,newnames) renames categories in a categorical array. By default, renamecats renames all categories. Elements of B use the new category names.

example

B = renamecats(A,oldnames,newnames) renames only the categories specified by oldnames.

example

Examples

collapse all

Create a categorical array that has abbreviations for New England state names.

A = categorical(["MA";"ME";"CT";"VT";"ME";"NH";"VT";"MA";"NH";"CT";"RI"])
A = 11x1 categorical
     MA 
     ME 
     CT 
     VT 
     ME 
     NH 
     VT 
     MA 
     NH 
     CT 
     RI 

Display the categories of A.

categories(A)
ans = 6x1 cell
    {'CT'}
    {'MA'}
    {'ME'}
    {'NH'}
    {'RI'}
    {'VT'}

Rename the categories to full state names instead of abbreviations.

newnames = ["Connecticut" "Massachusetts" "Maine" "New Hampshire" "Rhode Island" "Vermont"];
B = renamecats(A,newnames)
B = 11x1 categorical
     Massachusetts 
     Maine 
     Connecticut 
     Vermont 
     Maine 
     New Hampshire 
     Vermont 
     Massachusetts 
     New Hampshire 
     Connecticut 
     Rhode Island 

Display the categories of B.

categories(B)
ans = 6x1 cell
    {'Connecticut'  }
    {'Massachusetts'}
    {'Maine'        }
    {'New Hampshire'}
    {'Rhode Island' }
    {'Vermont'      }

Create a categorical array.

A = categorical(["purple" "blue" "purple" "red" "red" "blue"])
A = 1x6 categorical
     purple      blue      purple      red      red      blue 

Display its categories.

categories(A)
ans = 3x1 cell
    {'blue'  }
    {'purple'}
    {'red'   }

Change the category name purple to violet.

B = renamecats(A,"purple","violet")
B = 1x6 categorical
     violet      blue      violet      red      red      blue 

Display the new categories. Note that when violet replaced purple it did not change the order of the categories. They are no longer in alphabetical order.

categories(B)
ans = 3x1 cell
    {'blue'  }
    {'violet'}
    {'red'   }

Input Arguments

collapse all

input array, specified as a categorical array.

New category names, specified as a string array, character vector, or cell array of character vectors. The new category names must be unique, and must not duplicate any existing names.

Old category names, specified as a string array, character vector, or cell array of character vectors.

Tips

  • Renaming categories does not change their positions in categories(B). Use reordercats to change the category ordering. For example, you can use B = reordercats(B,sort(categories(B))) to put the categories in alphabetical order.

Extended Capabilities

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

Version History

Introduced in R2013b