MATLAB: Extract and code gender string as number using if loop

if loopstrcmpstrings

I have data for 200 participants stored in a 1×1 structure with 3 fields (time data, gender and age). I'm trying to include lines of script that will extract the gender of each participant and code their gender as 0 (non-binary), 1 (female), or 2 (male). I'm also assigning an ID and extracting age, code so far is below:
for i = 1:size(files);
id = str2num(files(i).name(7:size(files(i).name,2)-4));
tempfile = load(files(i).name);
age = tempfile.data.age;
end
I don't have experience in using an if-loop on strings and am struggling to find the best command to use. I have tried the below, as this is what I would do if extracting and coding numbers, but obviously this doesn't work for these strings as they are not matched in size. I've also played around with STRCMP and STRNCMP but with no luck.
if tempfile.data.gender == 'non-binary'
gender = 0;
elseif tempfile.data.gender == 'female'
gender = 1;
elseif tempfile.data.gender == 'male'
gender = 2;
A little help would be much appreciated!

Best Answer

  • I do not udnerstand the reason strcmp or strncmp would not work with your structure data. We may have to see ‘tempfile.data.gender’ in order to understand the problem.
    Meanwhile, consider strcmpi to do case-insensitive comparisons.