MATLAB: Hello, any one help me, i want to find the fastest way to solve the next problem:

cell arraysfindstrings

Here is the deal: I have the next cell of strings (for example)
cellstr = 'Cla' 'Ble' 'Cli 'Blo' 'Cle'
next i use "strfind( )" to find certain string in this cell, so lets say I want to find the word that has the Characters "B" and "e". The code i'm using is:
FindB = strfind(cellstr, 'B') => FindB = [] [1] [] [1] [].
Finde = strfind(cellstr, 'e') => Finde = [] [1] [] [] [1]
So how can i now the intersection of these 2, so i can say where the word "Ble" is without having to loop throught all the elements. I want to do these with cells arrays of 10000 elements.
(sorry for bad English). Thanks. C├ęsar Correa.

Best Answer

  • Do not name your variable cellstr as it's also a matlab function.
    There are many, many ways to achieve what you want. One way:
    str = {'Cla', 'Ble', 'Cli', 'Blo', 'Cle'};
    charstomatch = 'Be'; %order does not matter.
    ismatch = cellfun(@(s) all(ismember(charstomatch, s)), str)
    Another, using the new string class in R2016b:
    str = {'Cla', 'Ble', 'Cli', 'Blo', 'Cle'};
    sstr = string(str);
    ismatch = sstr.contains('B') & sstr.contains('e')
    Another, using your strfind:
    str = {'Cla', 'Ble', 'Cli', 'Blo', 'Cle'};
    ismatch = ~cellfun(@isempty, strfind(str, 'B')) & ~cellfun(@isempty, strfind(str, 'e'))
    Or using a regular expression:
    str = {'Cla', 'Ble', 'Cli', 'Blo', 'Cle'};
    ismatch = ~cellfun(@isempty, regexp(str, '(B[^e]*e)|(e[^B]*B)', 'once'))