strmatch
is
not recommended. Use strncmp
instead.
To find possible partial matches for a character vector, use strncmp
or
validatestring
, depending on your requirements.
strncmp
returns the numeric index of all array elements
that begin with the specified character vector, whereas
validatestring
returns a single character vector that
represents the best match to the specified character vector. To find an exact
match for a character vector, use strcmp
.
For instance, if your code currently contains lines such as these:
list = {'max', 'minimax', 'maximum', 'max'}
x = strmatch('max',list)
MATLAB returns the numeric indices of the list
array
elements that begin with max
:
x =
1
3
4
Replace strmatch
with one of the following:
validatestring
MATLAB returns the character vector representing the best match, and if multiple or no matches exist, returns an error.
For instance, this code returns a character vector:
list = {'max', 'minimax', 'maximum', 'max'}
x = validatestring('max', list)
x =
max
strncmp
MATLAB returns a logical array indicating which character vectors match the specified character vector.
For instance, if you specify this code:
list = {'max', 'minimax', 'maximum', 'max'}
x = strncmp('max', list, 3)
MATLAB returns logical value true (1) to indicate that the first,
third, and fourth list
elements begin with
max
and logical value false (0) to indicate that
the second list
element does not begin with
max
.
x =
1 0 1 1
If you prefer for MATLAB to return the numeric indices of
list
, use find
, as
follows:
list = {'max', 'minimax', 'maximum', 'max'}
x = find(strncmp(list, 'max', 3))
If your input to strmatch
is a character matrix, then first
convert the matrix to a cell array using cellstr
. Then, pass
the output from cellstr
to strncmp
or
validatestring
. For example, if your code is currently
this:
x = strmatch('max', char('max','minimax', 'maximum', 'max'))
Replace it with this:
list = cellstr(char('max', 'minimax', 'maximum', 'max'))
x = strncmp('max', list, 3)
MATLAB returns:
x =
1
0
1
1