Converting categorical data to prespecified numbers

4 views (last 30 days)
Hi,
I have a categorical array : ['SC' 'SC' 'SC' 'SC' 'SC' 'SC' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'MI' 'MI' 'MI' 'MI' 'MI' 'MI' 'MI' 'MI' 'MN' 'MN' 'MN' 'MN' 'MN' 'MN'];
I want to convert each category to a number of my choice: for instance SC should be 23, GA=10;MI=13,MN=15 etc... How can I do so?

Accepted Answer

Guillaume
Guillaume on 8 May 2018
keys = categorical({'SC', 'GA', 'MI', 'MN'});
values = [23, 10, 13, 15];
[found, where] = ismember(yourcategoricalarray, keys)
correspondingvalues = nan(size(yourcategoricalarray));
correspondingvalues(found) = values(where(found));
correspondingvalues will be nan for those entries you don't care about.

More Answers (1)

Ameer Hamza
Ameer Hamza on 8 May 2018
You can do the do this as follow,
data = {'SC' 'SC' 'SC' 'SC' 'SC' 'SC' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA'...
'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA'...
'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA' 'GA'...
'GA' 'GA' 'GA' 'GA' 'MI' 'MI' 'MI' 'MI' 'MI' 'MI' 'MI' 'MI' 'MN' 'MN'...
'MN' 'MN' 'MN' 'MN'};
dataCategorical = categorical(data);
tablePattern = categorical({'SC', 'GA', 'MI', 'MN'}); % make list of all unique pattern
valueValue = [23, 10, 13, 15]; % make list of all values corrosponding to unique patterns
index = (dataCategorical' == tablePattern)*(1:4)';
data2Value = valueValue(index);
  6 Comments
Guillaume
Guillaume on 8 May 2018
Note that you could have used the same method as in my answer (construct nan matrix, then fill with valueValue(index)) with Ameer's method. However using ismember is probably faster and certainly a lot less demanding in memory than the 2D array generated by the implicit expansion of ==

Sign in to comment.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!