Lesson 2.2

Characters and Strings


  • Understand what a character/string is.
  • Implement strings and characters in MATLAB.
  • Discover how strings/characters are different than other data in MATLAB.

What Is a Character?

A character, or “char” in MATLAB, is a data type (we will cover what “data types” are in a subsequent lesson) that as simple as a one single unit: a text character. This can be a symbol, letter, punctuation, space, etc.

In MATLAB, you can turn text into characters by using single quotes ('some characters'). The text will then turn purple signifying that MATLAB now recognizes the text as characters, and has stored it that way.

Important Note: If it is a character, MATLAB does not recognize numbers, variables, functions, etc. as anything except a text unit. For example, '2+2' as a string of characters does not equal 4. It is only text.

Example 1: Defining a Single Character
%Defining some very simple examples of characters exChar1 = '1' exChar2 = 'n' exChar3 = 'x' %Without recognizing the text as a character, MATLAB will think it is a variable and ask the %computer for its value. You can verify this for yourself by removing the quotes on exChar2 or %exChar3 (e.g., exChar = n). Command Window Output
exChar1 = 1 exChar2 = n exChar3 = x [Try this code yourself with Octave Online! Click Here]

What Is a String?

A set of characters, such as 'hey you', is referred to a string or a character array. A word or sentence stored in a character data type is essentially an array of individual characters, where each item in the character array is a separate entity and can be indexed/referenced.

You can specify a string directly by using MATLAB’s default syntax. For example, myVariable = 'cool_#123'. MATLAB will use the character data type to store this text assignment.

Example 2: Defining a String
myString = ‘Take 5!’; %Assigning a piece of text to a variable %Note: these reference commands will be covered shortly in the lesson on Vectors and Matrices myString(1) %The first letter in the character array (index 1) myString(2:4) %Range of letters in the character array, (index 2 through 4) Command Window Output
ans = T ans = ake [Try this code yourself with Octave Online! Click Here]

What Makes Characters/Strings Special?

Example 3 demonstrates some of the things we have talked about so far in this lesson. When using the characters, MATLAB will not recognize the text as variables, numbers, etc.

Next Lesson

In the next lesson, we will review a few ways to manipulate and work with characters and strings in MATLAB.