Valid Combinations of Text and Numeric Datatypes
Matrices and arrays can be composed of elements of almost any MATLAB® datatype as long as all elements in the matrix are of the same type. If you do include elements of unlike classes when constructing a matrix, MATLAB converts some elements so that all elements of the resulting matrix are of the same type.
Data type conversion is done with respect to a preset precedence of classes. The following
table shows six classes you can concatenate with an unlike type without generating an error.
The one exception in the table is that you cannot convert logical values to the
char data type.
TYPE | string | character | integer | single | double | logical |
|---|---|---|---|---|---|---|
string | string | string | string | string | string | string |
character | string | character | character | character | character | invalid |
integer | string | character | integer | integer | integer | integer |
single | string | character | integer | single | single | single |
double | string | character | integer | single | double | double |
logical | string | invalid | integer | single | double | logical |
For example, concatenating a double and single matrix
always yields a matrix of type single. MATLAB converts
the double element to single to
accomplish this.
x = single(1); y = double(2); z = [x y]
z =
1×2 single row vector
1 2Concatenating other data-types with a string converts the other data-types to string and adds them as new elements to a string array.
s = "Hello"; c = 'world'; x = [1 2 3]; newstr = [s c x]
newstr =
1×5 string array
"Hello" "world" "1" "2" "3"You can append other data-types as text to a string by using the +
operator. When a scalar is combined with an array in this fashion, text is appended to each
element.
s = "Hello"; c = 'world'; x = [1 2 3]; newstr = s + c + x
newstr =
1×3 string array
"Helloworld1" "Helloworld2" "Helloworld3"