Using the C++ Math Library | ![]() ![]() |
Creating MATLAB Character Arrays
MATLAB represents characters in 16-bit, Unicode format. You can create MATLAB strings using any of the following array creation mechanisms:
mwArray
constructorThe following sections provide more detail about creating arrays with each of these mechanisms, highlighting areas where the C++ syntax is significantly different from the corresponding MATLAB syntax.
Using the Character Array Constructor
The easiest way to create a MATLAB character string is to pass a standard C++ character string to the mwArray
string constructor.
mwArray A("my string"); cout << "A = " << A << endl;
This code produces the following output:
'my string'
Converting Numeric Arrays to Character Arrays
To convert a numeric array into a character array, use the char_func()
routine. The following code creates an array of numeric values and then converts it into a string.
mwArray C,D; C = horzcat(109,121,32,115,116,114,105,110,103); D = char_func(C); cout << D << endl;
This code produces the following output:
'my string'
To convert this character array back into its underlying numeric representation in double precision format, use the double_func()
routine.
Creating Multidimensional Arrays of Strings
You can create a multidimensional array of MATLAB character strings; however, each string must have the same length. The MATLAB C Math Library routines that create arrays of character strings pad the strings with blanks to make them all a uniform length.
Note To create a multidimensional character array where individual strings aren't padded with blanks, use cell arrays. See page 3-28 for more information. |
The following code fragment uses the char_func()
routine to create a two-dimensional array of strings from two strings of different lengths.
mwArray Z("my string"); mwArray Y("my dog"); mwArray Q = char_func(Z,Y); cout << Q << endl;
This code fragment produces the following output. Note how char_func()
adds three blanks to the string "my dog
" to make it the same length as "my string
", creating a 2-by-9 character array.
[ 'my string'; 'my dog '; ]
![]() | Character Arrays | Cell Arrays | ![]() |