MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Represent Text with Character and String Arrays


There are two ways to represent text in MATLAB®. You can store text in character arrays.
A typical use is to store short pieces of text as character vectors. And starting in R2016b,
you can also store multiple pieces of text in string arrays. String arrays provide a set of
functions for working with text as data.

Represent Text with Character Vectors

Create a character vector by enclosing a sequence of characters in single quotation
marks. MATLAB® displays character vectors using single quotation marks.

chr = 'Hello, world'

chr =
'Hello, world'

Character vectors store characters as 1-by-n vectors. You can index directly into
character vectors to get characters, or to change them.

chr(1:5)

ans =
'Hello'

chr(1:5) = 'HELLO';
chr

chr =
'HELLO, world'

You can work with character vectors just as you would with arrays of any other type. For
example, you can concatenate character vectors.

street = '123 Maple St.';
city = 'Lakeview, MA 01234';
fullAddress = [street ', ' city]

fullAddress =
'123 Maple St., Lakeview, MA 01234'

Typical uses for character vectors include specifying file names, plot labels, or input
arguments for functions. For more information on character arrays, see “Create
Character Arrays” on page 6-6.

6 Characters and Strings

Free download pdf