Table Of Contents

Text strings

A MATLAB string is an array of type char.

Creating character arrays

A character variable is automatically created when a string is assigned to it. For example, the statement:

>> a ='hi there'

a =
hi there

creates a 8-element character array (all spaces count). The output of whos for this array is:

>> whos a
  Name      Size            Bytes  Class    Attributes

  a         1x8                16  char

A special function ischar can be used to check for character arrays. If a given variable is of type character, then ischar returns a true (1) value. Otherwise, it returns a false (0) value. For example:

>> b=1; ischar(b)

ans =

>> ischar(a)

ans =

It is also possible to concatenate two character arrays the same way we do for numeric arrays. We just have to make sure the dimensions of two arrays agree:

>> a = 'good '; b = 'morning';
>> whos a b
  Name      Size            Bytes  Class    Attributes

  a         1x5                10  char
  b         1x7                14  char

>> c = [a b]

c =
good morning

(Notice we have put a space after good when defining a.) In the above example, both a and b are arrays (or vectors) with the same number of rows. With the same principle, it is possible to create n-dimensional character arrays, but each row of such an array must have exactly the same length. For example:

>> a = ['john' ; 'kate' ; 'anna' ]

a =

>> whos a
  Name      Size            Bytes  Class    Attributes

  a         3x4                24  char

Since a is an array, the number of columns in each row must be the same. Therefore, in character arrays, all rows must contain words that have the same number of characters (here’s 4).

However, it is also possible to produce character arrays with some rows having different lengths. The easiest way is to use char function. This function will automatically pad all strings to the length of the largest input string:

>> name = char('jitkomut','john')

name =

>> whos name
  Name      Size            Bytes  Class    Attributes

  name      2x8                32  char

You can also use indexing techniques like what we have for numeric arrays. For example, a(1,3) returns h, a(2,:) returns kate, etc. The transpose operation also works for character arrays:

>> a'

ans =


(but it’s just meaningless to do this operation.)

String conversion

Function str2num or str2double converts character strings into an equivalent double value. For example, a containing the characters 3.141592 can be converted to numeric form by:

>> a = '3.141592'; whos a
  Name      Size            Bytes  Class    Attributes

  a         1x8                16  char

>> b = str2num(a); whos b
  Name      Size            Bytes  Class     Attributes

  b         1x1                 8  double

(note that b is a numeric variable.) Likewise, we can convert a numeric value to a string using num2str command:

>> c = 23*24

c =

>> d = ['The product of 23 and 24 is ' num2str(c)]

d =
The product of 23 and 24 is 552

>> whos d
  Name      Size            Bytes  Class    Attributes

  d         1x31               62  char

In the above example, c is a double variable with value 552. The variable d is obtained by concatenating the string The product of 23 and 24 is and the string conversion of the number 552.

Built-in commands for strings

Most commands for strings are used to check whether if a condition is true. These commands return either a true value (1) or a false value (0).

  • strcmp determines if two strings are identical:

    >> a = 'hello'; b = 'Hello'; strcmp(a,b)
    ans =

(This command is case sensitive.) You can use strcmpi to check if two strings are identical ignoring case.

  • eval executes string with MATLAB expression:

    >> str = 'x = 12'; eval(str)
    x =
    >> n = 2; str = ['M' num2str(n) ' = eye(n)']
    str =
    M2 = eye(n)
    >> eval(str)
    M2 =
         1     0
         0     1

The above example shows that str is a concatenation of three strings; M, n (after the conversion from a numerical value), and = eye(n). The eval command takes string input and executes it as a MATLAB expression. This command is very useful when we have to execute a series of commands containing a mixture of string and numbers that should be generated automatically. For example, we can do a loop to assign values 1,2,3,... to n and generate M1,M2,M3,... automatically.

  • disp displays a string:

    >> disp(['The value of X is ' num2str(10)])
    The value of X is 10
  • fprintf prints a formatted numerical value with related texts:

    >> fprintf('%.3f \n',1/eps)

This shows the value of 1/eps (epsilon) into a float format with 3 decimal digits. When \n is inserted, MATLAB will enter a new line after printing the number. Other formats of float objects can be shown in the following table.

Some common format strings

Format Results
%d display value as an integer
%e display value in exponential format
%f display value in floating point format
%g display value in either floating or exponential format, whichever is shorter
\n skip to a new line
  • sprintf is a similar command to fprintf but it writes formatted data into string:

    >> str = sprintf('%d',round(pi))
    str =
    >> whos str
      Name      Size            Bytes  Class    Attributes
      str       1x1                 2  char

This assigns a rounded value of pi as an integer (specified by the format %d) as a string to the variable str.

Therefore, we can use sprintf or fprintf to print a numeric and string data on to the screen (or assign it to a variable.) For example, if x is a given number, say x = 4 and we want to print the message:

The value of x^2 is 16

(where the value of 16 should be calculated by MATLAB), then we can type:

>> x = 4;
>> fprintf('The value of x is %.2f \n',x^2)
The value of x is 16

Another example is to use sprintf to create two strings as follows:

>> str1 = sprintf('x is %d',x)

str1 =

x is 4

>> str2 = sprintf('sin(x) is %.3f',sin(x))

str2 =

sin(x) is -0.757

Then str1 and str2 are character variables and we can concatenate them together by:

>> disp([str1 ' and ' str2])

x is 4 and sin(x) is -0.757

This example shows how to concatename three strings, str1, str2 and `` and `` as a single character vector and use disp command to print its value on the screen.