Finding elements in string or cell array with common strings

16 ビュー (過去 30 日間)
Saeid
Saeid 2022 年 4 月 25 日
コメント済み: Saeid 2022 年 4 月 27 日
Consider two arrays A & B:
A={'blah_12_blah' 'blah_456_blah' 'blah_789_blah' 'blah_NPQZ_blah'}
B={'blah_NPQZ_blah' 'blah_135_blah' 'blah_579_blah' 'blah_12_blah' 'blah_RSTX_blah'}
The termn 'blah' basically refers to any string that comes before and after the parts of interest and each 'blah' could be a different string.
I would like to compare these two arrays and fine only the members that have the "part of interest" in common. In this case it means that after comparing A & B, only the elements 'blah_12_blah' and 'blah_NPQZ_blah' will show up as output, since these elements have the parts '12' and 'NPQZ' incommon, no matter what their respective 'blah' parts are.

採用された回答

Kevin Holly
Kevin Holly 2022 年 4 月 25 日
A={'blah_12_blah' 'blah_456_blah' 'blah_789_blah' 'blah_NPQZ_blah'}
A = 1×4 cell array
{'blah_12_blah'} {'blah_456_blah'} {'blah_789_blah'} {'blah_NPQZ_blah'}
B={'blah_NPQZ_blah' 'blah_135_blah' 'blah_579_blah' 'blah_12_blah' 'blah_RSTX_blah'}
B = 1×5 cell array
{'blah_NPQZ_blah'} {'blah_135_blah'} {'blah_579_blah'} {'blah_12_blah'} {'blah_RSTX_blah'}
A_partofinterest = extractBetween(A,'_','_')
A_partofinterest = 1×4 cell array
{'12'} {'456'} {'789'} {'NPQZ'}
B_partofinterest = extractBetween(B,'_','_')
B_partofinterest = 1×5 cell array
{'NPQZ'} {'135'} {'579'} {'12'} {'RSTX'}
A_new = A(ismember(A_partofinterest,B_partofinterest))
A_new = 1×2 cell array
{'blah_12_blah'} {'blah_NPQZ_blah'}
B_new = B(ismember(B_partofinterest,A_partofinterest))
B_new = 1×2 cell array
{'blah_NPQZ_blah'} {'blah_12_blah'}
  5 件のコメント
Kevin Holly
Kevin Holly 2022 年 4 月 27 日
A={'123abc' '456klm' '1a2b3c'}
A = 1×3 cell array
{'123abc'} {'456klm'} {'1a2b3c'}
B={'blah123abcblah' 'blah789ijkblah' 'blah11aa22bbblah' '123abc' '456pqr' '1a2b3c'}
B = 1×6 cell array
{'blah123abcblah'} {'blah789ijkblah'} {'blah11aa22bbblah'} {'123abc'} {'456pqr'} {'1a2b3c'}
contains(B,A)
ans = 1×6 logical array
1 0 0 1 0 1
B(contains(B,A))
ans = 1×3 cell array
{'blah123abcblah'} {'123abc'} {'1a2b3c'}
Saeid
Saeid 2022 年 4 月 27 日
Cool, thanks!

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by