MATLAB: Obtaining the mapping of categories to indices when using ‘grp2idx’

MATLAB

I would like to convert my categorical vector of labels to a numeric index vector and then convert my numeric labels back into categories.
How can I convert new index labels back to categorical labels ?
i.e how do I know the mapping from 'class name' to 'index' that the 'grp2idx' function uses ?

Best Answer

You can use 'grp2ind' to convert an array from categorical to numeric indices.
To understand the mapping of a category to the numeric index, you can use the 'categories' function.
To demonstrate, let 'c' be our categorical vector of labels :
>> c = categorical({'Male','Female','Female','Male','Female'})
Now, convert it to numeric indices using :
>> nums = grp2idx(c);
To get the mapping of a category to the indices/integers :
>> order_cat = categories(c);
Now,
if you want to get the numeric index that the 'Male' category corresponds to, you can use :
>> m = find(order_cat == "Male") %This is basically the index of the "Male" category in 'order_cat'
or if you want to convert a new vector of index labels back into categorical labels, you can simply use the 'categorical' function as below:
>> categorical(nums, [1:size(order_cat)], order_cat)