The problem with "contains"
조회 수: 5 (최근 30일)
이전 댓글 표시
I have an string array containing longer strings, let's say it is called LongStrings. Then I have an array of shorter strings, and I want to see if LongStrings contains and of the elements of the ShortStrings array. I can already do that by writing:
LongStrings={'Apples are red' 'Lemons are yellow' 'Cucmbers are green' 'Some numbers are odd' 'This house is big' 'Bananas are yellow too' 'Strawberries are red'}
ShortStrings={'odd' 'red' 'big' 'yellow'}
LongStringIdx=find(contains(LongStrings,ShortStrings))'
This already gives me the indices of elements of LongStrings that contain those in the ShortStrings, but I wonder how I can assign each value from the LongStringIdx to its analogue in the ShortStrings. In other woords, I would like to have an output like the one below, in which it not only tells me which element in LongStrings has any of the elements of ShortString, but which element of ShortStrings it is.
Idx=[1 2;2 4; 4 1; 5 3; 6 4; 7 2]
댓글 수: 1
Paul
2024년 1월 5일
What should the result be if an element of LongStrings contains two or more elements of ShortStrings?
채택된 답변
Paul
2024년 1월 6일
Might not be faster, but ....
LongStrings={'Apples are red' 'Lemons are yellow' 'Cucmbers are green' 'Some numbers are odd' 'This house is big' 'Bananas are yellow too' 'Strawberries are red'};
ShortStrings={'odd' 'red' 'big' 'yellow' 'Apples'};
[r,c] = find(cell2mat(cellfun (@(c) (contains(LongStrings(:),c)),ShortStrings,'Uni',false)));
sortrows([r,c])
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!