Main Content

将文本转换为数字值

This example shows how to convert text to the numeric values that it represents. Typically, you need to perform such conversions when you have text that represents numbers to be plotted or used in calculations. For example, the text might come from a text file or spreadsheet. If you did not already convert it to numeric values when importing it into MATLAB®, you can use the functions shown in this example.

您可以将字符串数组,字符矢量和字符矢量的单元格数转换为数字值。文本可以代表十六进制或二进制值,尽管当您将其转换为数字时,它们被存储为十进制值。您也可以将代表日期和时间的文本转换为datetimeor期间值,可以像数字值一样对待。

Double-Precision Values

将文本转换为双重精确值的推荐方法是使用str2double功能。它可以转换字符向量,字符串数组和字符向量的单元格数组。

例如,使用单个引号创建一个字符向量,然后将其转换为其代表的数字。

x = str2double('3.1416'
x = 3.1416

如果输入参数是字符串数组或字符向量的单元格数组,则str2double将其转换为具有相同大小的数字阵列。您可以使用双引号创建字符串。(琴弦有细绳数据类型,而字符向量具有chardata type.)

str =[“ 2.718”,,,,“ 3.1416”;“ 137”,,,,“ 0.015”这是给予的
str =2x2字符串“ 2.718”“ 3.1416”“ 137”“ 0.015”
x = str2double(str)
x =2×22.7180 3.1416 137.0000 0.0150

str2double函数可以转换包括逗号(作为千分之一)和小数点的文本。例如,您可以使用str2double转换Balance下表中的变量。Balance将数字表示为字符串,使用逗号作为数千分离器。

加载平衡平衡
平衡=3×2桌Customer Balance _________ ___________ "Diaz" "13,790.00" "Johnson" "2,456.10" "Wu" "923.71"
t.balance = str2double(t. balance)
t =3×2桌客户余额_________ _______“ Diaz” 13790“ Johnson” 2456.1“ Wu” 923.71

如果str2double无法将文本转换为一个数字,然后返回价值。

While thestr2num功能也可以将文本转换为数字,是不是recommended.str2num使用评估功能,当文本输入包含函数名称时,这可能会导致意外副作用。为了避免这些问题,请使用str2double

As an alternative, you can convert strings to double-precision values using the双倍的功能。如果输入是字符串数组,则双倍的返回具有相同大小的数字阵列,就像str2double做。但是,如果输入是字符向量,则双倍的converts the individual characters to numbers representing their Unicode values.

x =双倍的(“ 3.1416”
x = 3.1416
x =双倍的('3.1416'
x =1×651 46 49 52 49 54

This list summarizes the best practices for converting text to numeric values.

  • 要将文本转换为数字值,请使用str2double功能。它始终如一地处理字符串阵列,字符矢量和单元格阵列。

  • 您也可以使用双倍的字符串数组的功能。但是,它以不同的方式对待角色矢量。

  • 避免str2num。它称为评估可能会带来意外后果的功能。

十六进制和二进制值

您可以将十六进制和二进制数表示为文本或文字。当您将它们写为文字时,您必须使用0xand0b前缀。当您将它们表示为文本然后转换它们时,可以使用前缀,但不需要。

例如,将十六进制数字写为字面意思。需要前缀。

D = 0x3FF
D =uint161023

然后通过使用hex2dec功能。它识别前缀,但不需要。

d = hex2dec('3ff'
D = 1023
d = hex2dec('0x3ff'
D = 1023

使用代表二进制值的文本使用bin2dec功能。

D = bin2dec('101010'
d = 42
D = bin2dec('0B101010'
d = 42

日期和时间

MATLABprovides thedatetimeand期间data types to store dates and times, and to treat them as numeric values. To convert text representing dates and times, use thedatetimeand期间functions.

将代表日期的文本转换为datetime价值。这datetimefunction recognizes many common formats for dates and times.

C ='2019-09-20'
C = '2019-09-20'
D = datetime(C)
D =datetime2019年9月20日

You can convert arrays representing dates and times.

str =[“ 2019-01-31”,,,,“ 2019-02-28”,,,,"2019-03-31"这是给予的
str =1x3 string“ 2019-01-31”“ 2019-02-28”“ 2019-03-31”
d = datetime(str)
D =1x3 DateTime2019年1月31日至2019年2月28日2019年31月31日

如果you convert text to期间值,然后使用hh:mm:ssorDD:HH:MM:SS格式。

d =持续时间('12:34:56'
D =期间12:34:56

也可以看看

||||||

Related Topics