Programming |
In MATLAB, the term string refers to an array of Unicode characters. MATLAB represents each character internally as its corresponding numeric value. Unless you want to access these values, however, you can simply work with the characters as they display on screen.
You can use char
to hold an m
-by-n
array of strings as long as each string in the array has the same length. (This is because MATLAB arrays must be rectangular.) To hold an array of strings of unequal length, use a cell array.
The string is actually a vector whose components are the numeric codes for the characters. The actual characters displayed depend on the character set encoding for a given font.
Specify character data by placing characters inside a pair of single quotes. For example, this line creates a 1-by-13 character array called name
:
In the workspace, the output of whos
shows
You can see that each character uses two bytes of storage internally.
The class
and ischar
functions show name
's identity as a character array:
You can also join two or more character arrays together to create a new character array. Use either the string concatenation function, strcat
, or the MATLAB concatenation operator, []
, to do this. The latter preserves any trailing spaces found in the input arrays:
name = 'Thomas R. Lee'; title = ' Sr. Developer'; strcat(name,',',title) ans = Thomas R. Lee, Sr. Developer
To concatenate strings vertically, use strvcat
.
Creating Two-Dimensional Character Arrays
When creating a two-dimensional character array, be sure that each row has the same length. For example, this line is legal because both input rows have exactly 13 characters:
When creating character arrays from strings of different lengths, you can pad the shorter strings with blanks to force rows of equal length:
A simpler way to create string arrays is to use the char
function. char
automatically pads all strings to the length of the longest input string. In the following example, char
pads the 13-character input string 'Thomas R. Lee'
with three trailing blanks so that it will be as long as the second string:
When extracting strings from an array, use the deblank
function to remove any trailing blanks:
Identifying Logical Arrays | Cell Arrays of Strings |
© 1994-2005 The MathWorks, Inc.