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

71 views (last 30 days)
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 Comments
Walter Roberson
Walter Roberson on 3 Aug 2021
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.

Sign in to comment.

Accepted Answer

Vignesh Murugavel
Vignesh Murugavel on 4 Aug 2021
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 Comment
Stephen23
Stephen23 on 4 Aug 2021
"...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!

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!