Why am I returning NaN with str2double?
30 views (last 30 days)
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
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"
d1 = double(S1)
d2 = pi
d2a = double(d2)
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")
double(3)
Answers (1)
madhan ravi
on 7 Nov 2018
x = '3'
x = str2double(x)
See Also
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!