Programming  Cell Arrays of Strings

Creating strings in a regular MATLAB array requires that all strings in the array be of the same length. This often means that you have to pad blanks at the end of strings to equalize their length. However, another type of MATLAB array, the cell array, can hold different sizes and types of data in an array without padding. Cell arrays provide a more flexible way to store strings of varying length.

For details on cell arrays, see Cell Arrays.

Converting to a Cell Array of Strings

The `cellstr` function converts a character array into a cell array of strings. Consider the character array

• ```data = ['Allison Jones';'Development  ';'Phoenix      '];
```

Each row of the matrix is padded so that all have equal length (in this case, 13 characters).

Now use `cellstr` to create a column vector of cells, each cell containing one of the strings from the `data` array:

• ```celldata = cellstr(data)
celldata =
'Allison Jones'
'Development'
'Phoenix'
```

Note that the `cellstr` function strips off the blanks that pad the rows of the input string matrix:

• ```length(celldata{3})
ans =
7
```

The `iscellstr` function determines if the input argument is a cell array of strings. It returns a logical `1` (`true`) in the case of `celldata`:

• ```iscellstr(celldata)
ans =
1
```

Use `char` to convert back to a standard padded character array:

• ```strings = char(celldata)
strings =
Allison Jones
Development
Phoenix

length(strings(3,:))
ans =
13
```

Functions for Cell Arrays of Strings

This table describes the MATLAB functions for working with cell arrays.

 Function Description `cellstr` Convert a character array to a cell array of strings. `char` Convert a cell array of strings to a character array. `deblank` Remove trailing blanks from a string. `iscellstr` Return `true` for a cell array of strings. `sort` Sort elements in ascending or descending order. `strcat` Concatenate strings. `strcmp` Compare strings. `strmatch` Find possible matches for a string.

You can also use the following `set` functions with cell arrays of strings.

 Function Description `intersect` Set the intersection of two vectors. `ismember` Detect members of a set. `setdiff` Return the set difference of two vectors. `setxor` Set the exclusive OR of two vectors. `union` Set the union of two vectors. `unique` Set the unique elements of a vector. Characters and Strings String Comparisons © 1994-2005 The MathWorks, Inc.