Skip to content

MATLAB - Strings and Characters

Working with text is a fundamental part of programming, from reading data files to creating user interfaces. Modern MATLAB provides a powerful and intuitive string array type that makes text manipulation easier and more efficient than ever before.

It’s crucial to understand the two ways MATLAB handles text:

  • string (Double Quotes): This is the recommended modern approach. A string is a dedicated data type for text. String arrays can hold texts of different lengths without padding, and they come with a rich set of functions for manipulation. Use double quotes ("") to create strings.
  • char array (Single Quotes): This is the legacy approach. A char array is an array of individual characters. A 1xN char array is a ‘character vector’. To store multiple texts, you must use a MxN array where all rows have the same length (requiring padding with spaces) or use a cell array. You will still encounter this in older code.

Creating strings is simple. To combine them, you can use the plus (+) operator, which intuitively concatenates strings and even converts numbers to text automatically.

The string type has many built-in functions that are called using dot notation, making code highly readable. These replace older str* functions.

TaskModern string FunctionLegacy char Function
Find substringcontains(str, pattern)strfind, contains
Replace substringreplace(str, old, new)strrep
Split stringsplit(str, delimiter)strsplit, strtok
Join string arrayjoin(str_array, delimiter)strjoin
Convert to lower/upper caselower(str), upper(str)lower, upper
Check if starts/ends withstartsWith(str, pat), endsWith(str, pat)N/A (manual)
Get lengthstrlength(str)length

Imagine you have log entries and you need to extract specific information. string functions make this task simple.

You will inevitably encounter older code that uses char arrays. It’s easy to convert between the two types.

  • Use string for new code. Its benefits in flexibility, readability, and functionality are significant.
  • Use the + operator for simple concatenation. It’s clean and handles type conversion automatically.
  • Use join to combine elements of an array, and split to break them apart. They are more robust than manual looping.
  • Leverage function-form for clarity. Instead of str.lower(), using lower(str) is often more consistent with other MATLAB functions and can improve readability.
  • When performance is critical for very large text data, char arrays can sometimes be faster as they have less overhead. However, for most applications, the convenience of string arrays outweighs this.