2.11. Text Strings in MATLAB¶
We have already passed textual data to functions. What we have mostly
used so far are called character arrays, where each string is inside a
pair of single quote marks, ’Hello world’
. Character arrays have
been a part of MATLAB from its beginning, but a new data type of string
arrays was introduced with version R2016b and enhanced in version
R2017a. String arrays are created with either double quote marks
My String
or with the string()
function. String arrays have many
more functions to aid in manipulating textual data.
We might want to store a sequence of individual strings in a single array. Look at the following code to see a problem with character arrays and how strings and cell arrays improve handling of textual data. Each element of a cell array holds a reference to data, rather than actual data.
>> months1to3 = ['Jan', 'Feb', 'Mar']
months1to3 =
'JanFebMar'
>> months3 = ["January", "February", "March"];
>> months3
months3 =
1x3 string array
"January" "February" "March"
>> CellMonths1to3 = {'January', 'February', 'March'}
CellMonths1to3 =
1x3 cell array
'January' 'February' 'March'
MATLAB arrays of character arrays concatenate the string elements, which
in some cases is fine, but is often a problem. For this reason, we often
include spaces as part of character arrays, such as when we use disp
to combine textual and numeric data displayed to the user:
disp(['The answer is: ', num2str(x)])
See also
For more information about character arrays and strings, see MathWorks’ online documentation about Characters and Strings.
- Cell Arrays
One solution for passing textual data to functions is to use a cell array to store the data. Cell arrays are created with curly brackets
{ }
instead of square arrays used for numeric arrays[ ]
.A good application for using cell arrays is to set the tick labels on the axis of a plot, which is demonstrated in Tick Marks and Labels.
Cell arrays can store references to many types of data besides strings. Cell arrays hold references to data rather than the actual data. A cell array does not require homogeneous data types. So, for example, a string, character array, data structure, numeric vector, and a MATLAB object may reside together in the same cell array.