What's difference between str2num and str2double for converting an array to numeric values?

71 次查看(过去 30 天)
Hi, I have a 'char' array and want to convert it to a numeric array. when I use the function
str2num
I get the following error:
"Error using str2num (line 35)
Input must be a character vector or string scalar."
but I can change the format of the array using
str2double
can someone tell me why does the latter work?
  5 个评论
Walter Roberson
Walter Roberson 2021-8-3
str2num() will not work with cell array of character vectors.
str2double() will work with cell array of character vectors.
str2num() will work with char array with multiple rows.
str2double() will not work with char array with multiple rows.

请先登录,再进行评论。

采纳的回答

Vignesh Murugavel
str2num(chr) converts a character array or string scalar to a numeric matrix. The input can include spaces, commas, and semicolons to indicate separate elements. If str2num cannot parse the input as numeric values, then it returns an empty matrix.
The str2num function does not convert cell arrays or nonscalar string arrays, and is sensitive to spacing around + and - operators.
str2num() contains a call to eval(), which means that if your string has the same form as an array (e.g. with semicolons) then it is simply executed and the resulting array is returned. The problems with str2num() are that it doesn’t support cell arrays, and that because it uses an eval() function, wierd things can happen if your string includes a function call. str2double() is supposedly faster as well. So the general rule seems to be, use str2double() unless you are wanting to convert a string array of numbers to a numerical array.
There is one catch though- if you are converting a single number from a string to a number, then it would SEEM like str2num() and str2double() are interchangable, drop in replacements. However, if the string is not a number, they behave differently
  1 个评论
Stephen23
Stephen23 2021-8-4
"...unless you are wanting to convert a string array of numbers to a numerical array"
in which case SSCANF is much faster than STR2NUM.
"So the general rule seems to be"
use SSCANF if you can!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by