2.10. Text Strings in MATLABΒΆ

We have already passed strings of textual data to functions. Each string is inside a pair of single quote marks, 'Hello world'.

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 and the solution to the problem.

>> months1to3 = ['Jan', 'Feb', 'Mar']
months1to3 =
    'JanFebMar'
>> Months1to3 = ['January', 'February', 'March']
Months1to3 =
    'JanuaryFebruaryMarch'
>> CellMonths1to3 = {'January', 'February', 'March'}
CellMonths1to3 =
  1x3 cell array
    'January'    'February'    'March'

MATLAB arrays of strings concatenate the string elements, which in cases such as displaying data is fine. Arrays (vectors) do not work well to store a sequence of strings, especially when the each string is not the same length.

The solution 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.