Main Content

cast

Convert variable to different data type

Description

B = cast(A,newclass) returns the data in A converted to the data type (class) newclass, where newclass is the name of a built-in data type compatible with A. Any values in A that are outside the range of newclass are truncated in B to the nearest endpoint.

When converting a floating-point number to an integer, the cast function rounds the number to the nearest integer. If the floating-point number has a fractional part of exactly 0.5, then it rounds away from zero to the integer with larger magnitude.

example

B = cast(A,"like",p) converts A to the same data type and sparsity as the variable p. The complexity (real or complex) of B is determined by both A and p. If both A and p are real, then B is also real. Otherwise, B is complex.

example

Examples

collapse all

Convert int8 values to uint8.

Define a vector of 8-bit integers.

a = int8([-5 5]);

Convert a to unsigned 8-bit integers. The –5 value outside the range of uint8 is truncated to 0.

b = cast(a,"uint8")
b = 1x2 uint8 row vector

   0   5

Create a 1-by-3 vector of 32-bit signed integers.

A = int32([-12 34 56])
A = 1x3 int32 row vector

   -12    34    56

Create a complex number of the data type double.

p = 1+2i
p = 
1.0000 + 2.0000i

Convert A to the same data type and complexity as the variable p.

B = cast(A,"like",p)
B = 1×3 complex

 -12.0000 + 0.0000i  34.0000 + 0.0000i  56.0000 + 0.0000i

Create a 2-by-3 matrix of zeros whose elements are 32-bit unsigned integers.

A = zeros(2,3,"uint32")
A = 2x3 uint32 matrix

   0   0   0
   0   0   0

Create a 2-by-2 sparse matrix of the data type double.

p = sparse(2,2,pi)
p = 2x2 sparse double matrix (1 nonzero)
   (2,2)       3.1416

Convert A to the same data type and sparsity as the variable p.

B = cast(A,"like",p)
B = 2x3 sparse double matrix
   All zero

Input Arguments

collapse all

Input array, specified as a scalar, vector, matrix, or multidimensional array. The data type of A can be a built-in data type or other data type that supports conversion to the specified new data type.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char
Complex Number Support: Yes

New class, specified as "single", "double", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", "logical", or "char".

Prototype, specified as a scalar, vector, matrix, or multidimensional array. The data type of p can be a built-in data type or other compatible data type that supports conversion from the input data type.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char
Complex Number Support: Yes

Extended Capabilities

Version History

Introduced before R2006a

expand all