Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for a string in cell array in MATLAB?

Let's say I have the cell array

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'} 

What should I do if I want to find the index of 'KU'?

like image 680
Benjamin Avatar asked Nov 09 '11 06:11

Benjamin


People also ask

How do I find a string in a cell array?

x = strmatch(' str ',STRS) looks through the rows of the character array or cell array of strings STRS to find strings that begin with string str , returning the matching row indices. strmatch is fastest when STRS is a character array.

How do I check if something is in a cell array in MATLAB?

Description. tf = iscell( A ) returns 1 ( true ) if A is a cell array. Otherwise, it returns 0 ( false ).

Is string in cell array MATLAB?

String arrays are supported throughout MATLAB® and MathWorks® products. Therefore it is recommended that you use string arrays instead of cell arrays of character vectors. (However, MATLAB functions that accept string arrays as inputs do accept character vectors and cell arrays of character vectors as well.)

How do I find a specific string in MATLAB?

k = findstr( str1,str2 ) searches the longer of the two input arguments for any occurrences of the shorter argument and returns the starting index of each occurrence. If it finds no occurrences, then findstr returns the empty array, [] . The input arguments str1 and str2 can be character vectors or string scalars.


2 Answers

I guess the following code could do the trick:

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'} ind=find(ismember(strs,'KU')) 

This returns

ans =       2 
like image 191
Vidar Avatar answered Sep 25 '22 17:09

Vidar


>> strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}; >> tic; ind=find(ismember(strs,'KU')); toc 

Elapsed time is 0.001976 seconds.

>> tic; find(strcmp('KU', strs)); toc 

Elapsed time is 0.000014 seconds.

SO, clearly strcmp('KU', strs) takes much lesser time than ismember(strs,'KU')

like image 44
Pankaj Gupta Avatar answered Sep 24 '22 17:09

Pankaj Gupta