2.11. Text Strings in MATLABΒΆ
We have already passed textual data to functions. Actually, what we have used
so far are called character arrays where each string is inside a pair of single
quote marks, 'Hello world'
. Character arrays have always been a part of
MATLAB. But starting with version version R2016b and enhanced in version
R2017a, MATLAB has supported a new data type of string arrays. 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 doing so with character arrays and how strings and cell arrays provide solutions to the problem.
>> 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 data is fine, but often is 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
Read the MATLAB documentation about Characters and Strings.
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. See Tick Marks and Labels.
Note
Cell arrays are used to store many types of data besides strings. In terms of how cell arrays are used in MATLAB, you can think of a cell array as an array of pointers as you might have in a C language program.