Is there a function like string2double that can handle a numerical input?
14 ビュー (過去 30 日間)
古いコメントを表示
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!
0 件のコメント
採用された回答
Steven Lord
2019 年 1 月 21 日
First test if the input isnumeric. If it's not, try converting it from text data to a number.
2 件のコメント
その他の回答 (1 件)
Luna
2019 年 1 月 21 日
You can do it first convert to string then convert to numeric:
str2num(string(2))
str2num(string('2'))
Both gives you numeric 2.
5 件のコメント
Stephen23
2019 年 1 月 22 日
編集済み: Stephen23
2019 年 1 月 22 日
@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
2019 年 1 月 22 日
I will use recommended str2double then.
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!