| MATLAB® | ![]() |
| On this page… |
|---|
Converting from Numeric to String |
A character in the MATLAB software is actually an integer value converted to its Unicode® character equivalent. A character string is a vector with components that are the numeric codes for the characters. The actual characters displayed depend on the character set encoding for a given font.
The elements of a character or string belong to the char class. Arrays of class char can hold multiple strings, as long as each string in the array has the same length. (This is because MATLAB arrays must be rectangular.) To store an array of strings of unequal length, use a cell array.
Store a single character in the MATLAB workspace by enclosing the character in single quotation marks and assigning it to a variable:
hChar = 'h';
This creates a 1-by-1 matrix of class char. Each character occupies 2 bytes of workspace memory:
whos hChar Name Size Bytes Class Attributes hChar 1x1 2 char
The numeric value of hChar is 104:
uint8(hChar) ans = 104
Create a string by enclosing a sequence of letters in single quotation marks. MATLAB represents the five-character string shown below as a 1-by-5 vector of class char. It occupies 2 bytes of memory for each character in the string:
str = 'Hello'; whos str Name Size Bytes Class Attributes str 1x5 10 char
The uint8 function converts characters to their numeric values:
str_numeric = uint8(str) str_numeric = 72 101 108 108 111
The char function converts the integer vector back to characters:
str_alpha = char([72 101 108 108 111]) str_alpha = Hello
Create an array of strings in the same way that you would create a numeric array. Use the array constructor ([]), delimit each row in the array with a semicolon, and enclose each string in single quotation marks. Like numeric arrays, character arrays must be rectangular. That is, each row of the array must be the same length:
name = ['Thomas R. Lee'; ...
'Sr. Developer'; ...
'SFTware Corp.'];
Padding Strings. To make an array from strings that are originally of unequal length, you must either pad the shorter strings with space characters, or use a cell array. If you choose to pad the strings, there are two ways to do this. You can either add space characters manually, as shown here:
name = ['Harold A. Jorgensen '; ...
'Assistant Project Manager'; ...
'SFTware Corp. '];
or construct the array using the char function. This function automatically pads the shorter strings with spaces at the end. This array now consists of three strings of 25 characters each:
name = char('Harold A. Jorgensen', ...
'Assistant Project Manager', 'SFTware Corp.');
size(name)
ans =
3 25You can join two or more character arrays together to create a new character array. This is called concatenation and is explained for numeric arrays in the section Concatenating Matrices. To do this, use either the string concatenation function, strcat, or the MATLAB concatenation operator, []. The latter method preserves any trailing spaces found in the input arrays; the former method does not:
name = 'Thomas R. Lee'; title = 'Sr. Developer'; company = 'SFTware Corp.'; s = strcat(name, ', ', title, ', ', company); s = [name, ', ', title, ', ', company];
To concatenate strings vertically, use either the strvcat function or the [] operator with semicolons separating the rows:
s = strvcat(name, title, company); s = [name; title; company];
This command concatenates the value assigned to keyword matlabroot with the remainder of a path string:
dir([matlabroot '\extern\examples\mex\yprime.c']) yprime.c
Use any of the following functions to identify a character or string, or certain characters in a string:
| Function | Description |
|---|---|
| ischar | Determine whether the input is a character array. |
| isletter | Find all alphabetic letters in the input string. |
| isspace | Find all space characters in the input string. |
| isstrprop | Find all characters of a specific category. |
str = 'Find the space characters in this string';
% | | | | | |
% 5 9 15 26 29 34
find(isspace(str))
ans =
5 9 15 26 29 34The blanks function creates a string of space characters. The following example creates a string of 15 space characters:
s = blanks(15)
s =
To make the example more useful, append a '|' character to the beginning and end of the blank string so that you can see the output:
['|' s '|'] % Make result visible. ans = | |
Insert a few nonspace characters in the middle of the blank string:
s(6:10) = 'AAAAA'; ['|' s '|'] % Make result visible. ans = | AAAAA |
You can justify the positioning of these characters to the left or right using the strjust function:
sLeft = strjust(s, 'left'); ['|' sLeft '|'] % Make result visible. ans = |AAAAA | sRight = strjust(s, 'right'); ['|' sRight '|'] % Make result visible. ans = | AAAAA|
Remove all trailing space characters with deblank:
sDeblank = deblank(s); ['|' sDeblank '|'] % Make result visible. ans = | AAAAA|
Remove all leading and trailing spaces with strtrim:
sTrim = strtrim(s); ['|' sTrim '|'] % Make result visible. ans = |AAAAA|
Generally the MathWorks does not recommend expanding the size of an existing character array by assigning additional characters to indices beyond the bounds of the array such that part of the array becomes padded with zeros.
Creating strings in a regular MATLAB array requires that all strings in the array be of the same length. This often means that you have to pad blanks at the end of strings to equalize their length. However, another type of MATLAB array, the cell array, can hold different sizes and types of data in an array without padding. Cell arrays provide a more flexible way to store strings of varying length.
For details on cell arrays, see Cell Arrays in the Programming Fundamentals documentation.
The cellstr function converts a character array into a cell array of strings. Consider this character array:
data = ['Allison Jones';'Development ';'Phoenix '];
Each row of the matrix is padded so that all have equal length (in this case, 13 characters).
Now use cellstr to create a column vector of cells, each cell containing one of the strings from the data array:
celldata = cellstr(data)
celldata =
'Allison Jones'
'Development'
'Phoenix'
Note that the cellstr function strips off the blanks that pad the rows of the input string matrix:
length(celldata{3})
ans =
7
The iscellstr function determines if the input argument is a cell array of strings. It returns a logical 1 (true) in the case of celldata:
iscellstr(celldata)
ans =
1
Use char to convert back to a standard padded character array:
strings = char(celldata)
strings =
Allison Jones
Development
Phoenix
length(strings(3,:))
ans =
13
This table describes the MATLAB functions for working with cell arrays.
Function | Description |
|---|---|
Convert a character array to a cell array of strings. | |
Convert a cell array of strings to a character array. | |
Remove trailing blanks from a string. | |
Return true for acell array of strings. | |
Sort elements in ascending or descending order. | |
Concatenate strings. | |
Compare strings. | |
Find possible matches for a string. |
You can also use the following set functions with cell arrays of strings.
Function | Description |
|---|---|
Set the intersection of two vectors. | |
Detect members of a set. | |
Return the set difference of two vectors. | |
Set the exclusive OR of two vectors. | |
Set the union of two vectors. | |
Set the unique elements of a vector. |
The following MATLAB functions offer the capability to compose a string that includes ordinary text and data formatted to your specification:
sprintf — Write formatted data to an output string
fprintf — Write formatted data to an output file or the Command Window
warning — Display formatted data in a warning message
error — Display formatted data in an error message and abort
assert — Generate an error when a condition is violated
The syntax of each of these functions includes formatting operators similar to those used by the printf function in the C programming language. For example, %s tells MATLAB to interpret an input value as a string, and %d means to format an integer using decimal notation.
The general formatting syntax for these functions is
functionname(..., format_string, value1, value2, ..., valueN)
where the format_string argument expresses the basic content and formatting of the final output string, and the value arguments that follow supply data values to be inserted into the string.
Here is a sample sprintf statement, also showing the resulting output string:
sprintf('The price of %s on %d/%d/%d was $%.2f.', ...
'bread', 7, 1, 2006, 2.49)
ans =
The price of bread on 7/1/2006 was $2.49.The following sections cover
Note The examples in this section of the documentation use only the sprintf function to demonstrate how string formatting works. However, you can run the examples using the fprintf, warning, and error functions as well. |
The first input argument in the sprintf statement shown above is the format_string:
'The price of %s on %d/%d/%d was $%.2f.'
This argument can include ordinary text, formatting operators and, in some cases, special characters. The formatting operators for this particular string are: %s, %d, %d, %d, and %.2f.
Following the format_string argument are five additional input arguments, one for each of the formatting operators in the string:
'bread', 7, 1, 2006, 2.49
When MATLAB processes the format string, it replaces each operator with one of these input values.
Special Characters. Special characters are a part of the text in the string. But, because they cannot be entered as ordinary text, they require a unique character sequence to represent them. Use any of the following character sequences to insert special characters into the output string.
To Insert a . . . | Use . . . |
|---|---|
Single quotation mark | '' |
Percent character | %% |
Backslash | \\ |
Backspace | \b |
Form feed | \f |
New line | \n |
Carriage return | \r |
Horizontal tab | \t |
Hexadecimal number, N | \xN |
Octal number, N | \N |
In the syntax
functionname(..., format_string, value1, value2, ..., valueN)
The value arguments must immediately follow format_string in the argument list. In most instances, you supply one of these value arguments for each formatting operator used in the format_string. Scalars, vectors, and numeric and character arrays are valid value arguments. You cannot use cell arrays or structures.
If you include fewer formatting operators than there are values to insert, MATLAB reuses the operators on the additional values. This example shows two formatting operators and six values to insert into the string:
sprintf('%s = %d\n', 'A', 479, 'B', 352, 'C', 651)
ans =
A = 479
B = 352
C = 651You can also specify multiple value arguments as a vector or matrix. The format_string needs one %s operator for the entire matrix or vector:
mvec = [77 65 84 76 65 66];
sprintf('%s ', char(mvec))
ans =
MATLAB Sequential and Numbered Argument Specification.
You can place value arguments in the argument list either sequentially (that is, in the same order in which their formatting operators appear in the string), or by identifier (adding a number to each operator that identifies which value argument to replace it with). By default, MATLAB uses sequential ordering.
To specify arguments by a numeric identifier, add a positive integer followed by a $ sign immediately after the % sign in the operator. Numbered argument specification is explained in more detail under the topic Value Identifiers.
| Ordered Sequentially | Ordered By Identifier |
|---|---|
sprintf('%s %s %s', ...
'1st', '2nd', '3rd')
ans =
1st 2nd 3rd | sprintf('%3$s %2$s %1$s', ...
'1st', '2nd', '3rd')
ans =
3rd 2nd 1st |
Formatting operators tell MATLAB how to format the numeric or character value arguments and where to insert them into the string. These operators control the notation, alignment, significant digits, field width, and other aspects of the output string.
A formatting operator begins with a % character, which may be followed by a series of one or more numbers, characters, or symbols, each playing a role in further defining the format of the insertion value. The final entry in this series is a single conversion character that MATLAB uses to define the notation style for the inserted data. Conversion characters used in MATLAB are based on those used by the printf function in the C programming language.
Here is a simple example showing five formatting variations for a common value:
A = pi*100*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
ans =
314.159265 % Display in fixed-point notation (%f)
314.16 % Display 2 decimal digits (%.2f)
+314.16 % Display + for positive numbers (%+.2f)
314.16 % Set width to 12 characters (%12.2f)
000000314.16 % Replace leading spaces with 0 (%012.2f)The fields that make up a formatting operator in MATLAB are as shown here, in the order they appear from right to left in the operator. The rightmost field, the conversion character, is required; the five to the left of that are optional. Each of these fields is explained in a section below:
Conversion Character — Specifies the notation of the output.
Subtype — Further specifies any nonstandard types.
Precision — Sets the number of digits to display to the right of the decimal point.
Field Width — Sets the minimum number of digits to display.
Flags — Controls the alignment, padding, and inclusion of plus or minus signs.
Value Identifiers — Map formatting operators to value input arguments. Use the identifier field when value arguments are not in a sequential order in the argument list.
Here is an example of a formatting operator that uses all six fields. (Space characters are not allowed in the operator. They are shown here only to improve readability of the figure).

An alternate syntax, that enables you to supply values for the field width and precision fields from values in the argument list, is shown below. See the section Specifying Field Width and Precision Outside the format String for information on when and how to use this syntax. (Again, space characters are shown only to improve readability of the figure.)

Each field of the formatting operator is described in the following sections. These fields are covered as they appear going from right to left in the formatting operator, starting with the Conversion Character and ending with the Identifier field.
Conversion Character. The conversion character specifies the notation of the output. It consists of a single character and appears last in the format specifier. It is the only required field of the format specifier other than the leading % character.
Specifier | Description |
|---|---|
| c | Single character |
| d | Decimal notation (signed) |
| e | Exponential notation (using a lowercase e as in 3.1415e+00) |
| E | Exponential notation (using an uppercase E as in 3.1415E+00) |
| f | Fixed-point notation |
| g | The more compact of %e or %f. (Insignificant zeros do not print.) |
| G | Same as %g, but using an uppercase E |
| o | Octal notation (unsigned) |
| s | String of characters |
| u | Decimal notation (unsigned) |
| x | Hexadecimal notation (using lowercase letters a–f) |
| X | Hexadecimal notation (using uppercase letters A–F) |
This example uses conversion characters to display the number 46 in decimal, fixed-point, exponential, and hexadecimal formats:
A = 46*ones(1,4);
sprintf('%d %f %e %X', A)
ans =
46 46.000000 4.600000e+001 2ESubtype. The subtype field is a single alphabetic character that immediately precedes the conversion character. The following nonstandard subtype specifiers are supported for the conversion characters %o, %u, %x, and %X.
| b | The underlying C data type is a double rather than an unsigned integer. For example, to print a double-precision value in hexadecimal, use a format like '%bx'. |
| t | The underlying C data type is a float rather than an unsigned integer. |
Precision. precision in a formatting operator is a nonnegative integer that tells MATLAB how many digits to the right of the decimal point to use when formatting the corresponding input value. The precision field consists of a nonnegative integer that immediately follows a period and extends to the first alphabetic character after that period. For example, the specifier %7.3f, has a precision of 3.
Here are some examples of how the precision field affects different types of notation:
sprintf('%g %.2g %f %.2f', pi*50*ones(1,4))
ans =
157.08 1.6e+002 157.079633 157.08
Precision is not usually used in format specifiers for strings (i.e., %s). If you do use it on a string and if the value p in the precision field is less than the number of characters in the string, MATLAB displays only p characters of the string and truncates the rest.
You can also supply the value for a precision field from outside of the format specifier. See the section Specifying Field Width and Precision Outside the format String for more information on this.
For more information on the use of precision in formatting, see Setting Field Width and Precision.
Field Width. Field width in a formatting operator is a nonnegative integer that tells MATLAB the minimum number of digits or characters to use when formatting the corresponding input value. For example, the specifier %7.3f, has a width of 7.
Here are some examples of how the width field affects different types of notation:
sprintf('|%e|%15e|%f|%15f|', pi*50*ones(1,4))
ans =
|1.570796e+002| 1.570796e+002|157.079633| 157.079633|
When used on a string, the field width can determine whether MATLAB pads the string with spaces. If width is less than or equal to the number of characters in the string, it has no effect.
sprintf('%30s', 'Pad left with spaces')
ans =
Pad left with spacesYou can also supply a value for field width from outside of the format specifier. See the section Specifying Field Width and Precision Outside the format String for more information on this.
For more information on the use of field width in formatting, see Setting Field Width and Precision.
Flags. You can control the alignment of the output using any of these optional flags:
Character | Description | Example |
|---|---|---|
A minus sign (-) | Left-justifies the converted argument in its field | %-5.2d |
A plus sign (+) | Always prints a sign character (+ or –) | %+5.2d |
Zero (0) | Pad with zeros rather than spaces. | %05.2f |
Right- and left-justify the output. The default is to right-justify:
sprintf('right-justify: %12.2f\nleft-justify: %-12.2f', ...
12.3, 12.3)
ans =
right-justify: 12.30
left-justify: 12.30
Display a + sign for positive numbers. The default is to omit the + sign:
sprintf('no sign: %12.2f\nsign: %+12.2f', ...
12.3, 12.3)
ans =
no sign: 12.30
sign: +12.30Pad to the left with spaces or zeros. The default is to use space-padding:
sprintf('space-padded: %12.2f\nzero-padded: %012.2f', ...
5.2, 5.2)
ans =
space-padded: 5.20
zero-padded: 000000005.20Note You can specify more than one flag in a formatting operator. |
Value Identifiers. By default, MATLAB inserts data values from the argument list into the string in a sequential order. If you have a need to use the value arguments in a nonsequential order, you can override the default by using a numeric identifier in each format specifier. Specify nonsequential arguments with an integer immediately following the % sign, followed by a $ sign.
| Ordered Sequentially | Ordered By Identifier |
|---|---|
sprintf('%s %s %s', ...
'1st', '2nd', '3rd')
ans =
1st 2nd 3rd | sprintf('%3$s %2$s %1$s', ...
'1st', '2nd', '3rd')
ans =
3rd 2nd 1st |
This section provides further information on the use of the field width and precision fields of the formatting operator:
Effect on the Output String. The figure below illustrates the way in which the field width and precision settings affect the output of the string formatting functions. In this figure, the zero following the % sign in the formatting operator means to add leading zeros to the output string rather than space characters:

General rules for formatting
If precision is not specified, it defaults to 6.
If precision (p) is less than the number of digits in the fractional part of the input value (f), then only p digits are shown to the right of the decimal point in the output, and that fractional value is rounded.
If precision (p) is greater than the number of digits in the fractional part of the input value (f), then p digits are shown to the right of the decimal point in the output, and the fractional part is extended to the right with p-f zeros.
If field width is not specified, it defaults to precision + 1 + the number of digits in the whole part of the input value.
If field width (w) is greater than p+1 plus the number of digits in the whole part of the input value (n), then the whole part of the output value is extended to the left with w-(n+1+p) space characters or zeros, depending on whether or not the zero flag is set in the Flags field. The default is to extend the whole part of the output with space characters.
Specifying Field Width and Precision Outside the format String. To specify field width or precision using values from a sequential argument list, use an asterisk (*) in place of the field width or precision field of the formatting operator.
This example formats and displays three numbers. The formatting operator for the first, %*f, has an asterisk in the field width location of the formatting operator, specifying that just the field width, 15, is to be taken from the argument list. The second operator, %.*f puts the asterisk after the decimal point meaning, that it is the precision that is to take its value from the argument list. And the third operator, %*.*f, specifies both field width and precision in the argument list:
sprintf('%*f %.*f %*.*f', ...
15, 123.45678, ... % Width for 123.45678 is 15
3, 16.42837, ... % Precision for rand*20 is .3
6, 4, pi) % Width & Precision for pi is 6.4
ans =
123.456780 16.428 3.1416You can mix the two styles. For example, this statement gets the field width from the argument list and the precision from the format string:
sprintf('%*.2f', 5, 123.45678)
ans =
123.46
Using Identifiers In the Width and Precision Fields. You can also derive field width and precision values from a nonsequential (i.e., numbered) argument list. Inside the formatting operator, specify field width and/or precision with an asterisk followed by an identifier number, followed by a $ sign.
This example from the previous section shows how to obtain field width and precision from a sequential argument list:
sprintf('%*f %.*f %*.*f', ...
15, 123.45678, ...
3, 16.42837, ...
6, 4, pi)
ans =
123.456780 16.428 3.1416Here is an example of how to do the same thing using numbered ordering. Field width for the first output value is 15, precision for the second value is 3, and field width and precision for the third value is 6 and 4, respectively. If you specify field width or precision with identifiers, then you must specify the value with an identifier as well:
sprintf('%1$*4$f %2$.*5$f %3$*6$.*7$f', ...
123.45678, 16.42837, pi, 15, 3, 6, 4)
ans =
123.456780 16.428 3.1416
If any of the formatting operators in a string include an identifier field, then all of the operators in that string must do the same; you cannot use both sequential and nonsequential ordering in the same function call.
| Valid Syntax | Invalid Syntax |
|---|---|
sprintf('%d %d %d %d', ...
1, 2, 3, 4)
ans =
1 2 3 4 | sprintf('%d %3$d %d %d', ...
1, 2, 3, 4)
ans =
1 |
If your command provides more value arguments than there are formatting operators in the format string, MATLAB reuses the operators. However, MATLAB allows this only for commands that use sequential ordering. You cannot reuse formatting operators when making a function call with numbered ordering of the value arguments.
| Valid Syntax | Invalid Syntax |
|---|---|
sprintf('%d', 1, 2, 3, 4)
ans =
1234 | sprintf('%1$d', 1, 2, 3, 4)
ans =
1 |
Also, do not use identifiers when the value arguments are in the form of a vector or array:
| Valid Syntax | Invalid Syntax |
|---|---|
v = [1.4 2.7 3.1];
sprintf('%.4f %.4f %.4f', v)
ans =
1.4000 2.7000 3.1000 | v = [1.4 2.7 3.1];
sprintf('%3$.4f %1$.4f %2$.4f', v)
ans =
Empty string: 1-by-0 |
There are several ways to compare strings and substrings:
You can compare two strings, or parts of two strings, for equality.
You can compare individual characters in two strings for equality.
You can categorize every element within a string, determining whether each element is a character or white space.
These functions work for both character arrays and cell arrays of strings.
You can use any of four functions to determine if two input strings are identical:
strcmp determines if two strings are identical.
strncmp determines if the first n characters of two strings are identical.
strcmpi and strncmpi are the same as strcmp and strncmp, except that they ignore case.
Consider the two strings
str1 = 'hello'; str2 = 'help';
Strings str1 and str2 are not identical, so invoking strcmp returns logical 0 (false). For example,
C = strcmp(str1,str2)
C =
0Note For C programmers, this is an important difference between the MATLAB strcmp and C strcmp()functions, where the latter returns 0 if the two strings are the same. |
The first three characters of str1 and str2 are identical, so invoking strncmp with any value up to 3 returns 1:
C = strncmp(str1, str2, 2)
C =
1These functions work cell-by-cell on a cell array of strings. Consider the two cell arrays of strings
A = {'pizza'; 'chips'; 'candy'};
B = {'pizza'; 'chocolate'; 'pretzels'};Now apply the string comparison functions:
strcmp(A,B)
ans =
1
0
0
strncmp(A,B,1)
ans =
1
1
0You can use MATLAB relational operators on character arrays, as long as the arrays you are comparing have equal dimensions, or one is a scalar. For example, you can use the equality operator (==) to determine where the matching characters are in two strings:
A = 'fate';
B = 'cake';
A == B
ans =
0 1 0 1All of the relational operators (>, >=, <, <=, ==, ~=) compare the values of corresponding characters.
There are three functions for categorizing characters inside a string:
isletter determines if a character is a letter.
isspace determines if a character is white space (blank, tab, or new line).
isstrprop checks characters in a string to see if they match a category you specify, such as
Alphabetic
Alphanumeric
Lowercase or uppercase
Decimal digits
Hexadecimal digits
Control characters
Graphic characters
Punctuation characters
Whitespace characters
For example, create a string named mystring:
mystring = 'Room 401';
isletter examines each character in the string, producing an output vector of the same length as mystring:
A = isletter(mystring)
A =
1 1 1 1 0 0 0 0The first four elements in A are logical 1 (true) because the first four characters of mystring are letters.
MATLAB provides several functions for searching and replacing characters in a string. (MATLAB also supports search and replace operations using regular expressions. See Regular Expressions.)
Consider a string named label:
label = 'Sample 1, 10/28/95';
The strrep function performs the standard search-and-replace operation. Use strrep to change the date from '10/28' to '10/30':
newlabel = strrep(label, '28', '30') newlabel = Sample 1, 10/30/95
findstr returns the starting position of a substring within a longer string. To find all occurrences of the string 'amp' inside label, use
position = findstr('amp', label)
position =
2The position within label where the only occurrence of 'amp' begins is the second character.
The strtok function returns the characters before the first occurrence of a delimiting character in an input string. The default delimiting characters are the set of white-space characters. You can use the strtok function to parse a sentence into words. For example,
function allWords = words(inputString) remainder = inputString; allWords = ''; while (any(remainder)) [chopped,remainder] = strtok(remainder); allWords = strvcat(allWords, chopped); end
You can also use the textscan function to perform this task.
The strmatch function looks through the rows of a character array or cell array of strings to find strings that begin with a given series of characters. It returns the indices of the rows that begin with these characters:
maxstrings = strvcat('max', 'minimax', 'maximum')
maxstrings =
max
minimax
maximum
strmatch('max', maxstrings)
ans =
1
3The functions listed in this table provide a number of ways to convert numeric data to character strings.
Function | Description | Example |
|---|---|---|
Convert a positive integer to an equivalent character. (Truncates any fractional parts.) | [72 105] → 'Hi' | |
Convert a positive or negative integer to a character type. (Rounds any fractional parts.) | [72 105] → '72 105' | |
Convert a numeric type to a character type of the specified precision and format. | [72 105] → '72/105/' (format set to %1d/) | |
Convert a numeric type to a character type of the specified precision, returning a string MATLAB can evaluate. | [72 105] → '[72 105]' | |
Convert a positive integer to a character type of hexadecimal base. | [72 105] → '48 69' | |
Convert a positive integer to a character type of binary base. | [72 105] → '1001000 1101001' | |
Convert a positive integer to a character type of any base from 2 through 36. | [72 105] → '110 151' (base set to 8) |
The char function converts integers to Unicode character codes and returns a string composed of the equivalent characters:
x = [77 65 84 76 65 66]; char(x) ans = MATLAB
The int2str, num2str, and mat2str functions convert numeric values to strings where each character represents a separate digit of the input value. The int2str and num2str functions are often useful for labeling plots. For example, the following lines use num2str to prepare automated labels for the x-axis of a plot:
function plotlabel(x, y) plot(x, y) str1 = num2str(min(x)); str2 = num2str(max(x)); out = ['Value of f from ' str1 ' to ' str2]; xlabel(out);
Another class of conversion functions changes numeric values into strings representing a decimal value in another base, such as binary or hexadecimal representation. This includes dec2hex, dec2bin, and dec2base.
The functions listed in this table provide a number of ways to convert character strings to numeric data.
Function | Description | Example |
|---|---|---|
uintN (e.g., uint8) | Convert a character to an integer code that represents that character. | 'Hi' → 72 105 |
Convert a character type to a numeric type. | '72 105' → [72 105] | |
Similar to str2num, but offers better performance and works with cell arrays of strings. | {'72' '105'} → [72 105] | |
Convert a numeric type to a character type of specified precision, returning a string that MATLAB can evaluate. | 'A' → '-1.4917e-154' | |
Convert a character type of hexadecimal base to a positive integer. | 'A' → 10 | |
Convert a positive integer to a character type of binary base. | '1010' → 10 | |
Convert a positive integer to a character type of any base from 2 through 36. | '12' → 10 (if base == 8) |
Character arrays store each character as a 16-bit numeric value. Use one of the integer conversion functions (e.g., uint8) or the double function to convert strings to their numeric values, and char to revert to character representation:
name = 'Thomas R. Lee';
name = double(name)
name =
84 104 111 109 97 115 32 82 46 32 76 101 101
name = char(name)
name =
Thomas R. Lee
Use str2num to convert a character array to the numeric value represented by that string:
str = '37.294e-1';
val = str2num(str)
val =
3.7294
The str2double function converts a cell array of strings to the double-precision values represented by the strings:
c = {'37.294e-1'; '-58.375'; '13.796'};
d = str2double(c)
d =
3.7294
-58.3750
13.7960
whos
Name Size Bytes Class
c 3x1 224 cell
d 3x1 24 double
To convert from a character representation of a nondecimal number to the value of that number, use one of these functions: hex2num, hex2dec, bin2dec, or base2dec.
The hex2num and hex2dec functions both take hexadecimal (base 16) inputs, but hex2num returns the IEEE double-precision floating-point number it represents, while hex2dec converts to a decimal integer.
MATLAB provides these functions for working with character arrays:
Functions to Create Character Arrays
Function | Description |
|---|---|
Create the string specified between quotes. | |
Create a string of blanks. | |
Write formatted data to a string. | |
Concatenate strings. | |
Concatenate strings vertically. |
Functions to Modify Character Arrays
Function | Description |
|---|---|
Remove trailing blanks. | |
Sort elements in ascending or descending order. | |
Justify a string. | |
Replace one string with another. | |
Remove leading and trailing white space. | |
Functions to Read and Operate on Character Arrays
Function | Description |
|---|---|
Execute a string with MATLAB expression. | |
Read a string under format control. |
Functions to Search or Compare Character Arrays
Function | Description |
|---|---|
Find one string within another. | |
Compare strings. | |
Compare strings, ignoring case. | |
Find matches for a string. | |
Compare the first N characters of strings. | |
Compare the first N characters, ignoring case. | |
Find a token in a string. |
Functions to Determine Class or Content
Function | Description |
|---|---|
Return true for acell array of strings. | |
Return true for a character array. | |
Return true for letters of the alphabet. | |
Determine if a string is of the specified category. | |
Return true for white-space characters. |
Functions to Convert Between Numeric and String Classes
Function | Description |
|---|---|
Convert to a character or string. | |
Convert a character array to a cell array of strings. | |
Convert a string to numeric codes. | |
Convert an integer to a string. | |
Convert a matrix to a string you can run eval on. | |
Convert a number to a string. | |
Convert a string to a number. | |
Convert a string to a double-precision value. |
Functions to Work with Cell Arrays of Strings as Sets
Function | Description |
|---|---|
Set the intersection of two vectors. | |
Detect members of a set. | |
Return the set difference of two vectors. | |
Set the exclusive OR of two vectors. | |
Set the union of two vectors. | |
Set the unique elements of a vector. |
![]() | Logical Classes | Structures | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |