How do I find rows with certain nested strings?

조회 수: 1 (최근 30일)
Kris Govertsen
Kris Govertsen 2019년 6월 26일
답변: Image Analyst 2019년 6월 26일
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