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).
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.';
Use "strfind" to search "mystring" for the letter "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:
The number 12 is returned. This corresponds to the 12th character in the string, where the word "example" begins.
Michael Carroll is a high school mathematics teacher. He has written for various websites since 2010, specializing in programming, web design, electronics and various pieces of software. He holds a bachelor's degree in electrical engineering from the University of Texas, with specialization in embedded system design.