How do I find rows with certain nested strings?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Image Analyst
le 26 Juin 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 commentaires
Voir également
Catégories
En savoir plus sur Birthdays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!