How do I assign a value label to a string?

Im trying to assign values to 3 string variables of gender so that:
0=nonbinary
1=female
2=male
This is so that im able to add it as a predictor in a simple regression.
However, im not sure how to do this.

 Accepted Answer

It's not clear what you're trying to do but I think you have a list of stings and you're trying to assign them a numerical value according to their group.
gender = {'f' 'm' 'n' 'f' 'm' 'n'};
genderGroup = findgroups(gender); %matlab 2015b or later
If you'd like to assign specific values,
genderGroup = nan(size(gender));
genderGroup(strcmp(gender, 'f')) = 1;
genderGroup(strcmp(gender, 'm')) = 2;
genderGroup(strcmp(gender, 'n')) = 0;
However, if this group variable is used as a category in a regression function, you probably don't have to use numerical categories. You might be able to just convert your strings to categories.
categorical(gender)

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!