Programming and Data Types    


This section covers the following topics:

Creating Strings with Concatenation

Strings are often created by concatenating smaller elements together (e.g., strings, values, etc.). Two common methods of concatenating are to use the MATLAB concatenation operator ([]) or the sprintf function. The second and third line below illustrate both of these methods. Both lines give the same result:

For more information: See Creating Character Arrays, and Numeric/String Conversion in the MATLAB "Programming and Data Types" documentation

Comparing Methods of Concatenation

When building strings with concatenation, sprintf is often preferable to [] because

You can also concatenate using the strcat function, However, for simple concatenations, sprintf and [] are faster.

Store Arrays of Strings in a Cell Array

It is usually best to store an array of strings in a cell array instead of a character array, especially if the strings are of different lengths. Strings in a character array must be of equal length, which often requires padding the strings with blanks. This is not necessary when using a cell array of strings that has no such requirement.

The cellRecord below does not require padding the strings with spaces:

For more information: See Cell Arrays of Strings in the MATLAB "Programming and Data Types" documentation

Search and Replace Using Regular Expressions

Using regular expressions in MATLAB offers a very versatile way of searching for and replacing characters or phrases within a string. See the help on these functions for more information.

Match regular expression
Match regular expression, ignoring case
Replace string using regular expression

For more information: See Regular Expressions in the MATLAB "Programming and Data Types" documentation

Converting Between Strings and Cell Arrays

You can convert between standard character arrays and cell arrays of strings using the cellstr and char functions:

Also, a number of the MATLAB string operations can be used with either character arrays, or cell arrays, or both:

For more information: See Converting to a Cell Array of Strings," and String Comparisons in the MATLAB Programming and Data Types documentation

  Variables Evaluating Expressions