主要内容

cast

Convert variable to different data type

Description

example

B= cast(A,新级)convertsAto the data type (class)新级, where新级is the name of a built-in data type compatible withA。这castfunction truncates any values inAthat are outside the range of新级to the nearest endpoint.

将浮点数转换为整数时castfunction 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,'喜欢',p)convertsAto the same data type, sparsity, and complexity (real or complex) as the variablep。IfAp都是真实的B也是真实的。否则,Bis complex.

Examples

collapse all

Convertint8values touint8

Define a vector of 8-bit integers.

a = int8([ -  5 5]);

Convertato unsigned 8-bit integers. The –5 value outside the range ofuint8is truncated to 0.

b =cast(a,“uint8”)
b =1x2 uint8 row vector0 5

创建32位签名整数的1 x-3向量。

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

创建复杂数量的数据类型double

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

ConvertAto the same data type and complexity as the variablep

b =cast(A,'like',p)
b =1×3 complex-12.0000 + 0.0000i 34.0000 + 0.0000i 56.0000 + 0.0000i

创建一个2 x-3矩阵的零矩阵,其元素是32位未签名的整数。

a =零(2,3,'uint32')
A =2x3 uint32 matrix0 0 0 0 0 0

创建数据类型的2 by-2稀疏矩阵double

p =稀疏(2,2,pi)
p =(2,2)3.1416

ConvertAto the same data type and sparsity as the variablep

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|sym
Complex Number Support:Yes

New class, specified as'single','double','int8','int16','int32','int64',“uint8”,'uint16','uint32','uint64','logical','char','fi', or'sym'

原型,指定为标量,矢量,矩阵或多维数组。

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

兼容性考虑

expand all

Behavior changed in R2021b

Extended Capabilities

在R2006a之前引入