How to Find a Substring in MATLAB

by Michael Carroll

Strings of text are stored in MATLAB as vectors (single-row matrices). Individual characters in strings can be retrieved just as elements in a vector (e.g., stringname(4)). MATLAB also includes a number of commands to help you work with strings. Use the "strfind" command to search a string for a particular character or set of characters (substring).

Step 1

Type the following command in the Command Window to create a new string, being sure to use single quotation marks: mystring = 'This is an example string.';

Step 2

Use "strfind" to search "mystring" for the letter "i:" strfind(mystring,'i') The numbers 3, 6 and 23 are returned in a vector. These numbers correspond to the indices in "mystring" where "i" was found (the third, sixth and 23rd letters).

Use a string for the second argument to find a longer substring: strfind(mystring,'example') The number 12 is returned. This corresponds to the 12th character in the string, where the word "example" begins.

Video of the Day

Brought to you by Techwalla
Brought to you by Techwalla

More Articles