Ha Hacker
Ha Hacker

Reputation: 407

Find string (from table) in cell in matlab

I want to find the location of one string (which I take it from a table) inside of a cell: A is my table, and B is the cell.

I have tested :

strncmp(A(1,8),B(:,1),1)

but it couldn't find the location. I have tested many commands like: ismember,strmatch,find(strcmp),find(strcmpi)find(ismember),strfind and etc ... but they all give me errors mostly because of the type of my data !

So please suggest me a solution.

Upvotes: 3

Views: 13958

Answers (3)

Carl Witthoft
Carl Witthoft

Reputation: 21502

Modified solution from a Mathworks forum, for the case of a single-column table with ragged strings

find(strcmp('mystring',mytable{:,:}))

will give you the row number.

Upvotes: 0

Semjon Mössinger
Semjon Mössinger

Reputation: 1890

Luis Mendo's answer is absolotely correct, but I want to add some general information.

Your problem is that all the functions you tried (strfind, ...) only work for normal strings, but not for cell array. The way you index your A and B in your code snippet they still stay a cell array (of dimension (1,1)). You need to use curly brackets {} to "get rid of" the cell array and get the containign string. Luis Mendo shows how to do this.

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112669

You want strfind:

>> strfind('0123abcdefgcde', 'cde')
ans =
     7    12

If A is a table and B a cell array, you need to index this way:

strfind(B{1}, A.VarName{1});

For example:

>> A = cell2table({'cde'},'VariableNames',{'VarName'}); %// create A as table
>> B = {'0123abcdefgcde'}; %// create B as cell array of strings
>> strfind(B{1}, A.VarName{1})
ans =
     7    12

Upvotes: 3

Related Questions