Use the discretize function to create a categorical array by binning the values of x. Put all values
between zero and 15 in the first bin, all the values between 15 and 35 in the second bin, and all the
values between 35 and 50 in the third bin. Each bin includes the left endpoint, but does not include
the right endpoint.
catnames = ["small","medium","large"];
binnedData = discretize(x,[0 15 35 50],'categorical',catnames);
binnedData is a 100-by-1 ordinal categorical array with three categories, such that small <
medium < large.
Use the summary function to print the number of elements in each category.
summary(binnedData)
small
30
medium
35
large
35
Create Categorical Array from String Array
Starting in R2016b, you can create string arrays with the string function and convert them to
categorical array.
Create a string array that contains names of planets.
str = ["Earth","Jupiter","Neptune","Jupiter","Mars","Earth"]
str = 1x6 string
"Earth"
"Jupiter"
"Neptune"
"Jupiter"
"Mars"
"Earth"
Convert str to a categorical array.
planets = categorical(str)
planets = 1x6 categorical
Earth
Jupiter
Neptune
Jupiter
Mars
Earth
Add missing elements to str and convert it to a categorical array. Where str has missing values,
planets has undefined values.
str(8) = "Mars"
str = 1x8 string
Columns 1 through 6
"Earth"
"Jupiter"
"Neptune"
"Jupiter"
"Mars"
"Earth"
Columns 7 through 8
"Mars"
planets = categorical(str)
planets = 1x8 categorical
Columns 1 through 6
8 Categorical Arrays
8-4
between zero and 15 in the first bin, all the values between 15 and 35 in the second bin, and all the
values between 35 and 50 in the third bin. Each bin includes the left endpoint, but does not include
the right endpoint.
catnames = ["small","medium","large"];
binnedData = discretize(x,[0 15 35 50],'categorical',catnames);
binnedData is a 100-by-1 ordinal categorical array with three categories, such that small <
medium < large.
Use the summary function to print the number of elements in each category.
summary(binnedData)
small
30
medium
35
large
35
Create Categorical Array from String Array
Starting in R2016b, you can create string arrays with the string function and convert them to
categorical array.
Create a string array that contains names of planets.
str = ["Earth","Jupiter","Neptune","Jupiter","Mars","Earth"]
str = 1x6 string
"Earth"
"Jupiter"
"Neptune"
"Jupiter"
"Mars"
"Earth"
Convert str to a categorical array.
planets = categorical(str)
planets = 1x6 categorical
Earth
Jupiter
Neptune
Jupiter
Mars
Earth
Add missing elements to str and convert it to a categorical array. Where str has missing values,
planets has undefined values.
str(8) = "Mars"
str = 1x8 string
Columns 1 through 6
"Earth"
"Jupiter"
"Neptune"
"Jupiter"
"Mars"
"Earth"
Columns 7 through 8
"Mars"
planets = categorical(str)
planets = 1x8 categorical
Columns 1 through 6
8 Categorical Arrays
8-4
