MATLAB支持包括有符号和无符号整数以及单精度和双精度浮点数的各种数字类。默认情况下,MATLAB将所有数值存储为双精度浮点数。
您可以选择将任何数字或数组的数字存储为整数或单精度数字。
所有数字类型都支持基本的数组运算和数学运算。
转换为各种数值数据类型
MATLAB提供以下功能转换为各种数字数据类型 -
功能
目的
double
转换为双精度数
单
转换为单精度数
int8
转换为8位有符号整数
int16
转换为16位有符号整数
int32
转换为32位有符号整数
int64
转换为64位有符号整数
uint8
转换为8位无符号整数
uint16
转换为16位无符号整数
uint32
转换为32位无符号整数
uint64
转换为64位无符号整数
例
创建脚本文件并键入以下代码 -
x=single([5.323.476.28]).*7.5x=double([5.323.476.28]).*7.5x=int8([5.323.476.28]).*7.5x=int16([5.323.476.28]).*7.5x=int32([5.323.476.28]).*7.5x=int64([5.323.476.28]).*7.5
运行文件时,会显示以下结果 -
x =
39.900 26.025 47.100
x =
39.900 26.025 47.100
x =
38 23 45
x =
38 23 45
x =
38 23 45
x =
38 23 45
例
让我们再说一遍以上的例子。创建脚本文件并键入以下代码 -
x=int32([5.323.476.28]).*7.5x=int64([5.323.476.28]).*7.5x=num2cell(x)
运行文件时,会显示以下结果 -
x =
38 23 45
x =
38 23 45
x =
{
[1,1] = 38
[1,2] = 23
[1,3] = 45
}
最小和最大的整数
函数intmax()和intmin()返回可以用所有类型的整数表示的最大值和最小值。
这两个函数都使用整数数据类型作为参数,例如intmax(int8)或intmin(int64),并返回可以使用整数数据类型表示的最大值和最小值。
例
以下示例说明如何获取最小和最大的整数值。创建脚本文件并在其中写下面的代码 -
%displaying the smallestandlargestsignedinteger data
str="The range for int8 is:
%d to %d ";sprintf(str,intmin("int8"),intmax("int8"))str="The range for int16 is:
%d to %d ";sprintf(str,intmin("int16"),intmax("int16"))str="The range for int32 is:
%d to %d ";sprintf(str,intmin("int32"),intmax("int32"))str="The range for int64 is:
%d to %d ";sprintf(str,intmin("int64"),intmax("int64"))%displaying the smallestandlargestunsignedinteger data
str="The range for uint8 is:
%d to %d ";sprintf(str,intmin("uint8"),intmax("uint8"))str="The range for uint16 is:
%d to %d ";sprintf(str,intmin("uint16"),intmax("uint16"))str="The range for uint32 is:
%d to %d ";sprintf(str,intmin("uint32"),intmax("uint32"))str="The range for uint64 is:
%d to %d ";sprintf(str,intmin("uint64"),intmax("uint64"))
运行文件时,会显示以下结果 -
ans = The range for int8 is:
-128 to 127
ans = The range for int16 is:
-32768 to 32767
ans = The range for int32 is:
-2147483648 to 2147483647
ans = The range for int64 is:
0 to 0
ans = The range for uint8 is:
0 to 255
ans = The range for uint16 is:
0 to 65535
ans = The range for uint32 is:
0 to -1
ans = The range for uint64 is:
0 to 18446744073709551616
最小和最大的浮点数
函数realmax()和realmin()返回可以用浮点数表示的最大值和最小值。
当使用参数"single"调用这两个函数时,返回可以用单精度数据类型表示的最大值和最小值,当使用参数"double"调用时,返回您可以表示的最大值和最小值双精度数据类型。
例
以下示例说明如何获取最小和最大的浮点数。创建脚本文件并在其中写下面的代码 -
%displaying the smallestandlargest single-precision%floating point number
str="The range for single is:
%g to %g and
%g to %g";sprintf(str,-realmax("single"),-realmin("single"),...realmin("single"),realmax("single"))%displaying the smallestandlargestdouble-precision%floating point number
str="The range for double is:
%g to %g and
%g to %g";sprintf(str,-realmax("double"),-realmin("double"),...realmin("double"),realmax("double"))
运行文件时,会显示以下结果 -
ans = The range for single is:
-3.40282e+38 to -1.17549e-38 and
1.17549e-38 to 3.40282e+38
ans = The range for double is:
-1.79769e+308 to -2.22507e-308 and
2.22507e-308 to 1.79769e+308