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!
0 件のコメント
回答 (1 件)
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
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!