Is there a function like string2double that can handle a numerical input?
Mostra commenti meno recenti
Hi!
I am importing data that sometimes imports as a string, and sometimes as a number. In all cases I want a number. Is there a function like string2double that can handle a numerical input?
Right now it works like:
>> str2num('2')
ans =
2
>> str2num(2)
Error using str2num (line 35)
Input must be a character vector or string scalar.
Ideally it would work like:
>> FunctionLikestr2num('2')
ans =
2
>> FunctionLikestr2num(2)
ans =
2
Thank you!
Risposta accettata
Più risposte (1)
Luna
il 21 Gen 2019
You can do it first convert to string then convert to numeric:
str2num(string(2))
str2num(string('2'))
Both gives you numeric 2.
5 Commenti
Star Strider
il 21 Gen 2019
It is usually best to use str2double:
str2double(string(2))
str2double(string('2'))
Connor Brackley
il 21 Gen 2019
Luna
il 22 Gen 2019
@Luna: unfortunately str2num hides an eval call inside itself, which is why experienced MATLAB users try to avoid using it (especially inside loops). That is why str2double is recommended. The documentation states: "str2double Similar to str2num, but offers better performance and works with string arrays and cell arrays of character vectors."
Luna
il 22 Gen 2019
I will use recommended str2double then.
Categorie
Scopri di più su Data Type Conversion in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!