【Matlab】find string in cell array

https://in.mathworks.com/matlabcentral/answers/2015-find-index-of-cells-containing-my-stringcell array type:


Possible functions:
0. contains (Matlab v.2016b later)
1. strcmp: input is cell
2. cellfun + strfind
3. ismember
4. Define function by @
=======================

1. strcmp(s1,s2)
returns 'True' of the s1 and s2 are EXACTLY the same

Matlab document example
s1 = 'upon';
s2 = {'Once','upon';
      'a','time'};
tf = strcmp(s1,s2)
========
tf =

     0     1
     0     0
=======
s1 = 'on';
s2 = {'Once','upon';
      'a','time'};
tf = strcmp(s1,s2)
========
tf =

     0     0
     0     0

2. cellfun + strfind

IndexC = strfind(C, 'bla');
Index = find(not(cellfun('isempty', IndexC)));
or


X = find(~cellfun('isempty',strfind(cellstr(C),'bla')))

Note that there can not be an empty cell in the cell array C when using strfind.


3. ismember
[Lia,Locb] = ismember(A,B)
Lia if TRUE/FALSE, Locb is the location
Note that A should be EXACTLY the same in element of B
Matlab examples
A = {'dog','cat','fish','horse'};
B = {'dog ','cat','fish ','horse'};
[Lia,Locb] = ismember(A,B)
Lia =
     0     1     0     1
Locb =
     0     2     0     4
ismember treats trailing white space in cell arrays of strings as distinct characters.
4. Define function by @
cellfind = @(string)(@(cell_contents)(strcmp(string,cell_contents)));
You can then use this with cellfun to return a boolean value for each element of the cell. For example:
cell_array={1,eye(2),true,'foo',10};
string='foo'
logical_cells = cellfun(cellfind('foo'),cell_array)
logical_cells = 
                 [0,0,0,1,0]
reference: https://in.mathworks.com/matlabcentral/answers/2015-find-index-of-cells-containing-my-string

留言

熱門文章