How do I find rows with certain nested strings?
1 view (last 30 days)
Show older comments
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!
0 Comments
Answers (1)
Image Analyst
on 26 Jun 2019
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
0 Comments
See Also
Categories
Find more on Birthdays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!