Why am I returning NaN with str2double?

30 views (last 30 days)
Zack Rabas
Zack Rabas on 7 Nov 2018
Edited: Stephen23 on 15 Nov 2023
for example, i set:
x = 3
x = str2double(x)
and I get a return of NaN. The return should be 3. What am i doing wrong?
  4 Comments
Steven Lord
Steven Lord on 15 Nov 2023
The summary description of the str2double function from its documentation page is "Convert strings to double precision values". The number 3 isn't a string. Indeed, the description of the input argument states that it must be a "character vector | cell array of character vectors | string array". So perhaps to more clearly indicate when a user has called it incorrectly (with numeric data) it should throw an error when called with non-text data as input. That would be a backwards incompatibility, but perhaps it would be useful to avoid user confusion.
A alternative would be to switch your code from using char arrays or cell arrays of character vectors to use string arrays to store text data instead. If you do this, the double function would convert both a string containing the text representation of a number and a numeric scalar into a double precision value.
S1 = "3.1416"
S1 = "3.1416"
d1 = double(S1)
d1 = 3.1416
d2 = pi
d2 = 3.1416
d2a = double(d2)
d2a = 3.1416
Stephen23
Stephen23 on 15 Nov 2023
Edited: Stephen23 on 15 Nov 2023
"...so this seemingly simple problem becomes a real headache due to poor Matlab design choices."
As the name implies, STR2DOUBLE requires its input to be text of some kind. That is well documented.
But there is likely nothing stopping you from using string class data and DOUBLE():
double("3")
ans = 3
double(3)
ans = 3

Sign in to comment.

Answers (1)

madhan ravi
madhan ravi on 7 Nov 2018
x = '3'
x = str2double(x)
  2 Comments
madhan ravi
madhan ravi on 7 Nov 2018
because you didn't put string in and outside of 3 -> ' '
madhan ravi
madhan ravi on 7 Nov 2018
if you want to reverse it simply use
x = 3
x = num2str(x)

Sign in to comment.

Categories

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

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!