The problem with "contains"

5 ビュー (過去 30 日間)
Saeid
Saeid 2024 年 1 月 5 日
回答済み: Paul 2024 年 1 月 6 日
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'}
LongStrings = 1×7 cell array
{'Apples are red'} {'Lemons are yellow'} {'Cucmbers are green'} {'Some numbers are odd'} {'This house is big'} {'Bananas are yellow …'} {'Strawberries are red'}
ShortStrings={'odd' 'red' 'big' 'yellow'}
ShortStrings = 1×4 cell array
{'odd'} {'red'} {'big'} {'yellow'}
LongStringIdx=find(contains(LongStrings,ShortStrings))'
LongStringIdx = 6×1
1 2 4 5 6 7
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]
Idx = 6×2
1 2 2 4 4 1 5 3 6 4 7 2
  1 件のコメント
Paul
Paul 2024 年 1 月 5 日
What should the result be if an element of LongStrings contains two or more elements of ShortStrings?

サインインしてコメントする。

採用された回答

Paul
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])
ans = 7×2
1 2 1 5 2 4 4 1 5 3 6 4 7 2

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by