Converting categorical data to prespecified numbers

6 Ansichten (letzte 30 Tage)
Danielle Leblance
Danielle Leblance am 8 Mai 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?

Akzeptierte Antwort

Guillaume
Guillaume am 8 Mai 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.

Weitere Antworten (1)

Ameer Hamza
Ameer Hamza am 8 Mai 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 Kommentare
Danielle Leblance
Danielle Leblance am 8 Mai 2018
make them nan. I will look at Guillaume's answer
Guillaume
Guillaume am 8 Mai 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 ==

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by