Main Content

Combine Categorical Arrays

This example shows how to combine two categorical arrays.

Create Categorical Arrays

Create a categorical array, A, containing the preferred lunchtime beverage of 25 students in classroom A.

A = randi(3,[25,1]);
A = categorical(A,1:3,{'milk' 'water' 'juice'});

A is a 25-by-1 categorical array with three distinct categories: milk, water, and juice.

Summarize the categorical array, A.

     milk        6 
     water       5 
     juice      14 

Six students in classroom A prefer milk, five prefer water, and fourteen prefer juice.

Create another categorical array, B, containing the preferences of 28 students in classroom B.

B = randi(3,[28,1]);
B = categorical(B,1:3,{'milk' 'water' 'juice'});

B is a 28-by-1 categorical array containing the same categories as A.

Summarize the categorical array, B.

     milk        9 
     water       8 
     juice      11 

Nine students in classroom B prefer milk, eight prefer water, and eleven prefer juice.

Concatenate Categorical Arrays

Concatenate the data from classrooms A and B into a single categorical array, Group1.

Group1 = [A;B];

Summarize the categorical array, Group1.

     milk       15 
     water      13 
     juice      25 

Group1 is a 53-by-1 categorical array with three categories: milk, water, and juice.

Create Categorical Array with Different Categories

Create a categorical array, Group2, containing data from 50 students who were given the additional beverage option of soda.

Group2 = randi(4,[50,1]);
Group2 = categorical(Group2,1:4,{'juice' 'milk' 'soda' 'water'});

Summarize the categorical array, Group2.

     juice      12 
     milk       14 
     soda       10 
     water      14 

Group2 is a 50-by-1 categorical array with four categories: juice, milk, soda, and water.

Concatenate Arrays with Different Categories

Concatenate the data from Group1 and Group2.

students = [Group1;Group2];

Summarize the resulting categorical array, students.

     milk       29 
     water      27 
     juice      37 
     soda       10 

Concatenation appends the categories exclusive to the second input, soda, to the end of the list of categories from the first input, milk, water, juice, soda.

Use reordercats to change the order of the categories in the categorical array, students.

students = reordercats(students,{'juice','milk','water','soda'});

ans = 4x1 cell
    {'milk' }
    {'soda' }

Union of Categorical Arrays

Use the function union to find the unique responses from Group1 and Group2.

C = union(Group1,Group2)
C = 4x1 categorical

union returns the combined values from Group1 and Group2 with no repetitions. In this case, C is equivalent to the categories of the concatenation, students.

All of the categorical arrays in this example were nonordinal. To combine ordinal categorical arrays, they must have the same sets of categories including their order.

See Also

| | | | | |

Related Examples

More About