Help finding cell array indices for unique characters in string names

How might i search a cell array for indices corresponding to character strings containing, say, 'H2O' as part of the full name. Tried:
exact_match_mask = strcmp(names, 'H2O'); exact_match_locations = find(exact_match_mask);
but it only identifies index 4. I need to identify the abcH2Oxyz possibility to capture indices 4 and 10.
names = cell(1, 10);
names{1} = '*H';
names{2} = 'HO2';
names{3} = '*H2';
names{4} = 'H2O';
names{5} = 'H2O2';
names{6} = '*O';
names{7} = '*OH';
names{8} = '*O2';
names{9} = 'O3';
names{10} = 'H2O(S)';

4 件のコメント

Dyuman Joshi
Dyuman Joshi 2023 年 10 月 20 日
According to the criteria you mentioned i.e. "abcH2Oxyz", the 5th index should be captured as well.
But you have not mentioned it.
That means that there are some restrictions on what abc and xyz is supposed to be. Do you mind specifying more information about that?
Brantosaurus
Brantosaurus 2023 年 10 月 20 日
Apologies, yes you are correct the 5th also.
What i was trying to say is any combination of characters might come before and after H2O, including blank spaces.
Voss
Voss 2023 年 10 月 20 日
A more direct way of creating the cell array names is:
names = {'*H','HO2','*H2','H2O','H2O2','*O','*OH','*O2','O3','H2O(S)'};
Brantosaurus
Brantosaurus 2023 年 10 月 20 日
cheers for that :)

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

 採用された回答

All combined into one:
names = cell(1, 10);
names{1} = '*H';
names{2} = 'HO2';
names{3} = '*H2';
names{4} = 'H2O';
names{5} = 'H2O2';
names{6} = '*O';
names{7} = '*OH';
names{8} = '*O2';
names{9} = 'O3';
names{10} = 'H2O(S)';
[TF, IDX] = find(contains(names,"H2O"))
TF = 1×3
1 1 1
IDX = 1×3
4 5 10

1 件のコメント

Brantosaurus
Brantosaurus 2023 年 10 月 20 日
Fantastic. Many thanks for this.
The other contributions are also much appreciated :)

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

その他の回答 (1 件)

the cyclist
the cyclist 2023 年 10 月 20 日
names = cell(1, 10);
names{1} = '*H';
names{2} = 'HO2';
names{3} = '*H2';
names{4} = 'H2O';
names{5} = 'H2O2';
names{6} = '*O';
names{7} = '*OH';
names{8} = '*O2';
names{9} = 'O3';
names{10} = 'H2O(S)';
contains(names,'H2O')
ans = 1×10 logical array
0 0 0 1 1 0 0 0 0 1

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by