Documentation

# cast

Convert variable to different data type

## Syntax

``B = cast(A,newclass)``
``B = cast(A,'like',p)``

## Description

example

````B = cast(A,newclass)` converts `A` to the data type (class) `newclass`, where `newclass` is the name of a built-in data type compatible with `A`. The `cast` function truncates any values in `A` that are outside the range of `newclass` 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, sparsity, and complexity (real or complex) as the variable `p`. If `A` and `p` are both real, then `B` is also real. Otherwise, `B` is complex.```

## 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 = (2,2) 3.1416 ```

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

`B = cast(A,'like',p)`
```B = All zero sparse: 2x3 ```

## Input Arguments

collapse all

Input array, specified as a scalar, vector, matrix, or multidimensional array.

Data Types: `single` | `double` | `int8` | `int16` | `int32` | `int64` | `uint8` | `uint16` | `uint32` | `uint64` | `logical` | `char` | `fi`
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.

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