How do I find rows with certain nested strings?

1 次查看(过去 30 天)
I have a list of students:
Students=['Kerry';'Janet';'Cam';'Tyler']
their birthdays:
Birthdays=['June 1';'July 8';'December 2';'February 7']
and then a nested cell with their pets:
Pets={{'Cat','Fish'};{'Cat','Dog'};{'Bird','Fish'};{'Dog','Hamster'}}
I would like to find the indices of rows that corresponds to the students who have a Cat and or Bird, and eliminate the rows in all the arrays so I get the following information:
idXCatBird= %HELP IS NEEDED HERE
% Answer should be idXCatBird=[1;2;3];
Students=Students(idXCatBird);
Birthdays=Birthdays(idXCatBird);
Pets=Pets(idXCatBird);
I could do:
listCat = cellfun(@(listCat)strcmp(listCat,'Cat'),Pets,'UniformOutput',false);li
listCat=cellfun(@any,listCat)
listBird = cellfun(@(listBird)strcmp(listBird,'Bird'),Pets,'UniformOutput',false);li
listBird=cellfun(@any,listBird)
numCatBird=listCat+listBird;
[idxCatBird,~]=find(numCatBird)
But I was hoping there was a faster way!

回答(1 个)

Image Analyst
Image Analyst 2019-6-26
Try this:
catRows = any(contains(Pets, 'Cat'), 2)
catOwners = Students(catRows)
Here's a more complete demo:
Students = {'Kerry';'Janet';'Cam';'Tyler'}
% Their birthdays:
Birthdays = {'June 1';'July 8';'December 2';'February 7'}
% and then a nested cell with their pets:
Pets = {'Cat','Fish'; 'Cat','Dog'; 'Bird','Fish'; 'Dog','Hamster'}
% Find cat owners:
catRows = any(contains(Pets, 'Cat'), 2)
catOwners = Students(catRows)
% Now print out all the people who own each type of pet:
uniquePets = unique(Pets)
for k = 1 : length(uniquePets)
fprintf('Here are the owners of %s\n', uniquePets{k});
thisPet = uniquePets{k};
rows = any(contains(Pets, thisPet), 2);
petOwners = Students(rows)
end

类别

Help CenterFile Exchange 中查找有关 Birthdays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by