Surjya Narayana Padhi
Surjya Narayana Padhi

Reputation: 7841

How to find a substring in an array of strings in matlab?

I have a string 'ADSL'. I want to find this string in an array of strings char('PSTN,ADSL','ADSL,VDSL','FTTH,VDSL')

when i run this command

strmatch('ADSL',char('PSTN,ADSL','ADSL,VDSL','FTTH,VDSL'));

the output is 2 But I expect the output as [1 2]

strmatch only gives positive result if the search string appears at the begining of row.

How can I find the search string if it occurs anywhere in the row?

Upvotes: 1

Views: 3858

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112659

For an array of strings, it's better to use a cell array. That way strings can be of differnet lengths (and regexp can be applied on all cells at once):

cellArray = {'PSTN,ADSL','ADSL,VDSL','FTTH,VDSL'};
str = 'ADSL';

Then:

result = find(~cellfun('isempty', regexp(cellArray, str)));

will give what you want.

If you really have a char array as in your example,

array = char('PSTN,ADSL','ADSL,VDSL','FTTH,VDSL');

you can convert to a cell array (with cellstr) and apply the above:

result = find(~cellfun('isempty', regexp(cellstr(array), str)));

Upvotes: 1

mhmsa
mhmsa

Reputation: 475

i would use strfind

a=strfind(cellstr(char('PSTN,ADSL','ADSL,VDSL','FTTH,VDSL')),'ADSL');

in this case will be a three by one cell array containing the index where you string starts at in the corresponding string

Upvotes: 0

Amro
Amro

Reputation: 124563

Given the following input:

array = {'PSTN,ADSL', 'ADSL,VDSL', 'FTTH,VDSL'};
str = 'ADSL';

We find the starting position of each string match using:

>> pos = strfind(array, str)
pos = 
    [6]    [1]    []

or

>> pos = regexp(array, str)
pos = 
    [6]    [1]    []

We can then find the indices of matching strings using:

>> matches = find(~cellfun(@isempty,pos))
matches =
     1     2

Upvotes: 3

Related Questions