cast

Converts a value to another numeric or char class by name.

Category: Language Fundamentals > Data Types

Syntax

B = cast(A, newclass)

Returns A converted to the class named newclass.

B = cast(A, 'like', P)

Converts A to the class (and complexity) of the array P.

Description

cast(A, 'int8') behaves like calling int8(A): the result is rounded to the nearest integer and values outside the range saturate, so cast(300, 'uint8') is 255.

The point of cast is that the class is a variable, which helps in generic code that must produce the type of some other array.

Input arguments

A
Numeric, logical or char array.
newclass
Class name as text: 'double', 'single', 'int8' to 'int64', 'uint8' to 'uint64', 'logical' or 'char'.

Output arguments

B
Array of the same size as A, with class newclass.

Example

Choosing the class by name

cast(3.7, 'int8')
cast(300, 'uint8')
cls = 'single';
class(cast(1, cls))
Output
ans = int8
   4
ans = uint8
   255
ans = 'single'

See also

double int8 single class typecast