MATLAB string functions let you create, inspect, search, split, join, format, and modify text. For most new code, use string arrays, written with double quotes, and functions such as strlength, contains, replace, and split; use character vectors when working with older code or functions that specifically require them.
Strings and character vectors in MATLAB
MATLAB has two common ways to represent text. A string scalar uses double quotes, as in name = "Mira";. A character vector uses single quotes, as in name = 'Mira';. A string array can hold multiple text values, while a character vector is an array of individual characters. String arrays were introduced in MATLAB R2016b, so code written for earlier releases may rely heavily on character vectors and cell arrays of character vectors.
The distinction matters because text functions do not always accept the same input types or return the same type. For example, string('Mira') converts a character vector to a string scalar, while char("Mira") converts a string scalar to a character vector. Conversion is useful when combining modern code with older functions, but it is better to check the expected input type than to convert everything automatically.
- Use strings for convenient text values and arrays of text, especially in new code.
- Use character vectors when an existing function or codebase expects character data.
- Use cell arrays of character vectors when each cell must hold text of a different length in a legacy workflow.
Creating and combining text
Double-quoted text creates a string scalar, and a comma-separated set of string scalars creates a string array. For example, colors = ["red", "blue", "green"]; makes a 1-by-3 array. You can also convert other supported values with the string function. This is helpful when importing mixed data or preparing values for display, though conversion does not guarantee that every original value has a meaningful text representation.
For string scalars, the plus operator joins text: label = "Item " + "7"; produces "Item 7". The append function is another clear option for concatenating text. Character vectors are commonly joined horizontally inside brackets: label = ['Item ', '7'];. The strcat function is also used in MATLAB code to concatenate text inputs. Do not confuse these operations with numeric addition: the plus operator adds numbers when its inputs are numeric.
When you need to combine many string-array elements with a delimiter, use join. For instance, join(["red", "blue"], ", ") returns the string scalar "red, blue". The delimiter is part of the result between adjacent elements; it is not added before the first or after the last element.
Measuring text and checking values
Choose a measurement function based on what you mean by “length.” strlength reports the number of characters in string values, whereas numel counts array elements. For a string array with three names, numel(names) is 3, even if the names have different lengths. MATLAB’s length returns the size of the largest array dimension, so it is not a substitute for counting characters in each string.
For example, with words = ["sun", "cloud"];, strlength(words) returns [3 5], while numel(words) returns 2. The result from strlength is an array corresponding to the input values. If your data may include missing string values, ismissing can identify them; a missing string is not the same thing as an empty string such as "".
Use == or strcmp for case-sensitive equality checks, and strcmpi when the comparison should ignore letter case. For instance, strcmpi("MATLAB", "matlab") returns true. These comparisons are useful for checking labels and categories. For ordering or locale-sensitive text behavior, avoid assuming that a basic equality test answers broader questions about how words should be sorted.
Finding text and matching patterns
contains checks whether text includes a specified substring. With items = ["blue car", "red bike"];, contains(items, "car") returns a logical array with true for the first element and false for the second. Use startsWith or endsWith when the location matters, such as checking whether a filename begins with a prefix or ends in an extension.
These functions normally perform case-sensitive matching. Where supported, their IgnoreCase option can make a search case-insensitive. Make that choice explicit when text may arrive in inconsistent capitalization; otherwise, values such as "Error" and "error" may be treated as different. For a simple fixed phrase, contains is usually easier to read than a regular expression.
Regular expressions are useful when the pattern has a structure rather than a fixed sequence of characters. MATLAB provides functions including regexp for finding matches and regexprep for replacing them. For example, regexprep("Room 204", '\d+', '#') returns "Room #" because \d+ matches one or more digits in the regular-expression pattern. Regular expressions are powerful, but a plain text function is often clearer for ordinary substring searches.
Replacing, extracting, and cleaning text
Use replace for straightforward substitutions. For example, replace("blue car", "blue", "red") returns "red car". The function is useful for replacing known text without writing a pattern. For more elaborate rules, such as replacing every run of digits, use regexprep.
MATLAB also provides functions for extracting portions of text. extractBefore and extractAfter select text relative to a position or specified text, while extractBetween extracts text between boundaries. These can make parsing readable when the format is predictable. If the input format is irregular, consider validating it first rather than assuming the delimiter or boundary always exists.
Whitespace is a common source of unexpected mismatches. strip removes leading and trailing whitespace from text, while replace can handle a known unwanted sequence. For example, applying strip to a value read from a file can help prevent a trailing space from interfering with a comparison. Be deliberate: trimming text may change data where spaces are meaningful, such as carefully formatted identifiers.
Splitting and joining text
split breaks a string into pieces using a delimiter and returns a string array. For example, split("red,green,blue", ",") produces the three values "red", "green", and "blue". After editing or filtering the pieces, join can combine them again with a chosen separator. This pattern is useful for processing simple comma-separated labels or lists.
Do not treat a quick split as a complete CSV parser. Real CSV data can contain quoted fields, embedded commas, and line breaks, so splitting every row on commas can corrupt valid fields. For files with a defined table format, use MATLAB’s import tools or table-reading functions rather than building a parser from basic string operations. For older code that represents text as a cell array of character vectors, strjoin is a familiar way to join cell contents; check the function’s input requirements when moving between cell arrays and string arrays.
Formatting and converting values
Use compose to format values into string arrays. For example, compose("Run %d", [1 2 3]) produces strings such as "Run 1", "Run 2", and "Run 3". Its format specifiers follow the familiar style used by formatted output functions. sprintf is another option when you need formatted output as a character vector, often for compatibility with older code or an interface that expects that type.
When converting text that represents numbers, str2double is usually the practical choice. It converts numeric text to numeric values and returns NaN for text it cannot interpret as a number. For example, str2double(["12.5", "unknown"]) returns a numeric array containing 12.5 and NaN. Check for failed conversions before using the results in calculations; otherwise, an invalid text entry can quietly affect later results.
Common mistakes and choosing the right function
A frequent mistake is treating a string scalar as if it were a character vector. A string scalar is one text value; indexing a string array selects an element, whereas indexing a character vector selects a character. For example, word = 'cat'; word(1) gives the character 'c'. If you need to work with individual characters in a string, convert it to a character vector deliberately or use an operation designed for the task.
Another common issue is mixing strings, character vectors, and cell arrays without noticing the output type. When an error says an input type is unsupported, inspect the value with class and convert only where appropriate. Also check whether an operation returns a scalar, an array, or a cell array; matching the dimensions of text inputs matters when processing data element by element.
- For a fixed substring search, start with
contains,startsWith, orendsWith. - For exact or case-insensitive equality, use
strcmporstrcmpi. - For a simple substitution, use
replace; for pattern-based rules, considerregexprep. - For delimiter-separated text, use
splitandjoin, but use a proper import function for structured files such as CSV. - For numeric text, use
str2doubleand explicitly handle results that areNaN.
Older functions such as strfind and strrep still appear in existing MATLAB programs. They can be appropriate when maintaining older code, but newer code is often easier to read when it uses functions whose names describe the intended operation, such as contains and replace. Check the documentation for your MATLAB release if a function or option is unavailable, especially when sharing scripts across installations.
Frequently Asked Questions
What is the difference between a MATLAB string and a character array?
A string is a text value, written with double quotes, and can be part of a string array. A character vector is an array of characters, commonly written with single quotes. Many newer text functions work naturally with strings, while older code may expect character data.
How do I check whether a string contains a word?
Use contains(text, pattern). It returns a logical result for each input element. Matching is case-sensitive by default, so use an available case-insensitive option or normalize capitalization if that better fits the task.
How do I combine strings with a space or comma?
Use + or append for direct concatenation, and use join when combining elements of a string array with a repeated delimiter. For example, joining two names with ", " places a comma and space between them.
How do I get the number of characters in a MATLAB string?
Use strlength. Use numel to count the number of values in an array instead. These answer different questions: a two-element string array can contain two strings whose character lengths are, for example, 3 and 5.
Should I use strfind or contains?
Use contains when you only need a true-or-false answer about whether text occurs. strfind is found in older code and can return match positions, but it is not necessary for a basic presence check.
Related
- Assembly Split in CATIA: How to Separate a Product
- Balance Sheet Accounting: How It Works
- J Curve Balance of Payments: How It Works
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- How to Hide Filter Arrows in Excel and Keep Table FiltersTo hide filter arrows in Excel without removing a table’s AutoFilter setup, click inside the table, open Table…
- How to Open Filter in Excel With a Keyboard ShortcutTo turn filters on or off in Excel for Microsoft 365 on Windows, select a cell in your…
- Oracle RIGHT Function: How to Get Trailing CharactersOracle Database does not provide a built-in RIGHT() string function. To return the last characters of a string,…
- Excel Filter Shortcut: How to Turn Filters On and OffIn Excel for Microsoft 365 on Windows, press Ctrl+Shift+L to turn AutoFilter on or off. Select a cell…
- Excel Percentage Change Formula: Examples and Common ErrorsTo calculate percentage change in Excel, subtract the old value from the new value, divide by the old…
- Divide Symbol in Excel: How the / Operator Works in FormulasIn Microsoft Excel, the division operator is the forward slash, /. To divide one cell by another, enter…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.