Main Content

Combining Unlike Integer Types

Overview

If you combine different integer types in a matrix (e.g., signed with unsigned, or 8-bit integers with 16-bit integers), MATLAB® returns a matrix in which all elements are of one common type. MATLAB sets all elements of the resulting matrix to the data type of the leftmost element in the input matrix. For example, the result of the following concatenation is a vector of three 16-bit signed integers:

A = [int16(450) uint8(250) int32(1000000)]
A =

  1×3 int16 row vector

     450     250   32767

Example of Combining Unlike Integer Sizes

Concatenate the following two numbers once, and then switch their order. The return value depends on the order in which the integers are concatenated. The leftmost type determines the data type for all elements in the vector:

A = [int16(5000) int8(50)]
A =

  1×2 int16 row vector

   5000     50
B = [int8(50) int16(5000)]
B =

  1×2 int8 row vector

    50   127

The first operation returns a vector of 16-bit integers. The second returns a vector of 8-bit integers. The element int16(5000) is set to 127, the maximum value for an 8-bit signed integer.

The same rules apply to vertical concatenation:

C = [int8(50); int16(5000)]
C =

  2×1 int8 column vector

    50
   127

Note

You can find the maximum or minimum values for any MATLAB integer type using the intmax and intmin functions. For floating-point types, use realmax and realmin.

Example of Combining Signed with Unsigned

Now do the same exercise with signed and unsigned integers. Again, the leftmost element determines the data type for all elements in the resulting matrix:

A = [int8(-100) uint8(100)]
A =

  1×2 int8 row vector

   -100    100
B = [uint8(100) int8(-100)]
B =

  1×2 uint8 row vector

   100     0

The element int8(-100) is set to zero because it is no longer signed.

MATLAB evaluates each element prior to concatenating them into a combined array. In other words, the following statement evaluates to an 8-bit signed integer (equal to 50) and an 8-bit unsigned integer (unsigned -50 is set to zero) before the two elements are combined. Following the concatenation, the second element retains its zero value but takes on the unsigned int8 type:

A = [int8(50), uint8(-50)]
A =

  1×2 int8 row vector

   50    0

Related Topics