names = { 'amy' , 'chris' , 'john' , 'karin' , 'juan' }; gender = { 'female' , 'male' , 'male' , 'female' , 'male' }; create a list that returns all male names in matlab

One way to create a list that returns all male names in matlab is by using logical indexing with the gender variable. Here's how to do it:

main.m
names = {'amy', 'chris', 'john', 'karin', 'juan'};
gender = {'female', 'male', 'male', 'female', 'male'};

% create a logical index of all male names
is_male = strcmp(gender, 'male');

% use logical indexing to get all male names
male_names = names(is_male);
259 chars
9 lines

The variable is_male is a logical index of the same length as gender, with 1 where the corresponding gender is 'male' and 0 where it is not. We can use this logical index to select the male names from the names variable using square brackets with logical indexing. The result is a list of all male names: 'chris' and 'juan':

main.m
male_names =

  1×2 cell array

    {'chris'}    {'juan'}
58 chars
6 lines

gistlibby LogSnag