Getting Started Previous page   Next Page

Characters and Text

Enter text into MATLAB using single quotes. For example,

The result is not the same kind of numeric matrix or array you have been dealing with up to now. It is a 1-by-5 character array.

Internally, the characters are stored as numbers, but not in floating-point format. The statement

converts the character array to a numeric matrix containing floating-point representations of the ASCII codes for each character. The result is

The statement

reverses the conversion.

Converting numbers to characters makes it possible to investigate the various fonts available on your computer. The printable characters in the basic ASCII character set are represented by the integers 32:127. (The integers less than 32 represent nonprintable control characters.) These integers are arranged in an appropriate 6-by-16 array with

The printable characters in the extended ASCII character set are represented by F+128. When these integers are interpreted as characters, the result depends on the font currently being used. Type the statements

and then vary the font being used for the Command Window. Select Preferences from the File menu to change the font. If you include tabs in lines of code, use a fixed-width font, such as Monospaced, to align the tab positions on different lines.

Concatenation with square brackets joins text variables together into larger strings. The statement

joins the strings horizontally and produces

The statement

joins the strings vertically and produces

Note that a blank has to be inserted before the 'w' in h and that both words in v have to have the same length. The resulting arrays are both character arrays; h is 1-by-11 and v is 2-by-5.

To manipulate a body of text containing lines of different lengths, you have two choices -- a padded character array or a cell array of strings. When creating a character array, you must make each row of the array the same length. (Pad the ends of the shorter rows with spaces.) The char function does this padding for you. For example,

produces a 5-by-9 character array.

Alternatively, you can store the text in a cell array. For example,

creates a 5-by-1 cell array that requires no padding because each row of the array can have a different length.

You can convert a padded character array to a cell array of strings with

and reverse the process with


Previous page  Cell Arrays Structures Next page

© 1994-2005 The MathWorks, Inc.