Converting categorical data to prespecified numbers
6 views (last 30 days)
Show older comments
Danielle Leblance
on 8 May 2018
Edited: Walter Roberson
on 8 May 2018
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?
0 Comments
Accepted Answer
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.
0 Comments
More Answers (1)
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
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 ==
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!