7.4: Creating Character Vector

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    7.4: Creating Character Vector

    A character vector is a sequence of characters placed between single quotation marks. MATLAB stores a character vector as an array of individual characters. The following example creates the Hello World phrase using this method.

    Example \(\PageIndex{1}\)

    myChar = 'Hello World'

    The text looks similar to the string example, myString, but this variable is not a string. It is a character vector, which means MATLAB treats it like a row vector of characters.

    If we use the whos command, we can see that MATLAB stores them as different data types.

    The variable myString has the class string, while myChar has the class char.

    Exercise \(\PageIndex{1}\)
    myString = "Hello World";
    myChar = 'Hello World';
    
    whos

    This distinction is important because some MATLAB functions expect strings, while others expect character vectors. Also, strings and character vectors behave differently when they are placed into arrays, compared, concatenated, or converted.

    3.1 Indexing a Character Vector

    Because a character vector behaves like an array, we can index it to extract one character or a section of characters. Here is an example:

    Example \(\PageIndex{2}\)

    myName = 'Emily';

    firstLetter = myName(1)

    ending = myName(3:end)

    In this example, myName(1) gives the first character, which is E. The expression myName(3:end) gives the characters from position 3 through the end, which is ily.

    Caution

    Do not forget that spaces count as characters. In the character vector Hello World, there are 11 characters: 5 letters in Hello, 1 space, and 5 letters in World.


    This page titled 7.4: Creating Character Vector was last modified on Tue, 30 Jun 2026 02:11:53 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.