Why am I returning NaN with str2double?
Show older comments
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
Adithya Raajkumar
on 12 May 2022
There's no need to be snarky. In most other programming languages, conversion to numeric returns numeric if the data is already numeric. Ex. in R, as.numeric(4) returns 4. It's not unreasonable to hope that Matlab would have a similar functionality.
Ruben Krueger
on 15 Nov 2023
For anyone else confused by this function, str2double(x) for some reason returns "NaN" if x is a double. This doesn't match the behavior of any programming language I'm familar with. Thus, you need to check the type of x before calling str2double. Worse yet, Matlab doesn't have a ternary operator, so this seemingly simple problem becomes a real headache due to poor Matlab design choices.
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"
d1 = double(S1)
d2 = pi
d2a = double(d2)
"...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")
double(3)
Answers (1)
madhan ravi
on 7 Nov 2018
x = '3'
x = str2double(x)
2 Comments
madhan ravi
on 7 Nov 2018
because you didn't put string in and outside of 3 -> ' '
madhan ravi
on 7 Nov 2018
if you want to reverse it simply use
x = 3
x = num2str(x)
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!