Why am I returning NaN with str2double?

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

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.
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"
S1 = "3.1416"
d1 = double(S1)
d1 = 3.1416
d2 = pi
d2 = 3.1416
d2a = double(d2)
d2a = 3.1416
"...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)

x = '3'
x = str2double(x)

2 Comments

because you didn't put string in and outside of 3 -> ' '
if you want to reverse it simply use
x = 3
x = num2str(x)

Sign in to comment.

Categories

Products

Release

R2018b

Tags

Asked:

on 7 Nov 2018

Edited:

on 15 Nov 2023

Community Treasure Hunt

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

Start Hunting!