1

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?

1
  • If you have a cell array of strings, try strfind with cellfun as follows: cell2mat(cellfun(@(x) strfind(x,'ADSL'),a,'UniformOutput',false)) Commented Jun 30, 2014 at 15:46

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

cellfun('isempty', ...) may be faster than cellfun(@isempty, ...)
yes I think it is, though the difference is getting smaller: undocumentedmatlab.com/blog/… (see the comments as well)
1

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)));

1 Comment

the conversion from char-matrix to cell array of strings can be simplified using cellstr
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.