Categorical Arrays in MATLAB
Last Updated :
19 Oct, 2022
In MATLAB, categorical is a data type which can assign values from a finite, discrete set of values. For example, consider there are three categories, ‘positive’, ‘negative’, and ‘null’ so, a categorical array, which is an array of categorical data type, will only take data which has values from the above three categories. So, a categorical array from the above categories could be:
% categorical array example
cat_arr = {'null', 'positive', 'negative'};
This would create a 3×1 categorical array. Now, without much delay, let us see how these arrays could be created in various ways.
We can create a categorical array from an existing array.
Example 1:
Matlab
arr = { 'alive' , 'dead' , 'coma' };
arr = categorical(arr);
categories(arr)
|
Output:
The third statement in the above code gives the categories present in the array arr, see the output below
We can also add a category in the categorical array used above, which is not present in the original array. For example, say we want another category of patients ‘healed’ but, no such patient is currently present in hospital so, we can do that by creating an array of independent categories and then pass it to the categorical() function.
Example 2:
Matlab
valueset = { 'healed' , 'dead' , 'coma' , 'alive' };
arr = { 'alive' , 'dead' , 'coma' };
arr = categorical(arr, valueset);
categories(arr)
|
Output:
As we can see, the array is the same but, the number of categories is now 4, including the ‘healed’ category.
Let us see how to create empty categorical arrays.
Example 3:
Matlab
arr = NaN(1,3);
arr = categorical(arr);
cats=[ "dead" , "coma" , "alive" ];
arr=addcats(arr,cats);
categories(arr)
|
Output:
This would first convert an array of NaNs to a categorical array and then, using the addcats() function, it will add the cats categories to the array arr. The output is:
Assigning Categorical Values To arr:
Now, let us see how to assign values of to the created empty categorical array.
Example 4:
Matlab
arr = NaN(1,3);
arr = categorical(arr);
cats=[ "dead" , "coma" , "alive" ];
arr=addcats(arr,cats);
arr(1)= "dead" ;
arr(2)= "alive" ;
arr(3)= "dead" ;
disp(arr)
|
Output:
Note: The elements of a categorical array can be accessed the same way as of an ordinary array, using the smooth parenthesis () method.
Conclusion:
This article discussed various ways of creating categorical arrays, accessing its elements, and assigning values to the same.