Find index of pattern match

24 views (last 30 days)
Tiasa Ghosh
Tiasa Ghosh on 13 Aug 2018
Edited: Stephen23 on 13 Aug 2018
Hello! I am trying to find index position of a pattern from a string array in a string. for example:
string='Mary had a little lamb';
fcnset=["big","little","small"];
I would want the result as the index of 'little' from the string. I tried the following line, but it doesn't work:
n = find(contains(string,fcnset));
how do I go about it?

Accepted Answer

Stephen23
Stephen23 on 13 Aug 2018
Edited: Stephen23 on 13 Aug 2018
>> str = 'Mary had a little lamb';
>> pat = {'big','little','small'};
>> idx = ~cellfun('isempty',strfind(str,pat))
idx =
0 1 0
>> find(idx)
ans = 2
  2 Comments
Tiasa Ghosh
Tiasa Ghosh on 13 Aug 2018
I get the following error on running the same code
Stephen23
Stephen23 on 13 Aug 2018
Edited: Stephen23 on 13 Aug 2018
Aaah, sorry. Try one of these:
>> str = 'Mary had a little lamb';
>> pat = {'big','little','small'};
>> idx = ~cellfun('isempty',regexp(str,pat))
idx =
0 1 0
>> find(idx)
ans = 2
Or
>> str = 'Mary had a little lamb';
>> pat = {'big','little','small'};
>> fun = @(p)isempty(strfind(str,p));
>> idx = ~cellfun(fun,pat)
idx =
0 1 0
>> find(idx)
ans = 2
Or
contains

Sign in to comment.

More Answers (1)

KSSV
KSSV on 13 Aug 2018
Edited: KSSV on 13 Aug 2018
string='Mary had a little lamb';
fcnset=["big","little","small"];
idx = zeros(3,1) ;
for i = 1:3
idx(i) = contains(string,fcnset{i}) ;
end

Community Treasure Hunt

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

Start Hunting!