フィルターのクリア

What is the fastest way to determine whether a string is a number?

79 ビュー (過去 30 日間)
Patrick Mboma
Patrick Mboma 2014 年 7 月 3 日
コメント済み: Patrick Mboma 2014 年 7 月 4 日
Hi, I have a string x and in order to determine wether it is a number one can do the following
try
flag = isnumeric(eval(x));
catch
flag=false;
end
Is there a better and faster way to do this?
Thanks
Pat.

採用された回答

Sean de Wolski
Sean de Wolski 2014 年 7 月 3 日
編集済み: Sean de Wolski 2014 年 7 月 3 日
Probably:
isnan(str2double(str))
This won't need try/catch either.
Anything with eval in it will definitely not be fast.
  1 件のコメント
Patrick Mboma
Patrick Mboma 2014 年 7 月 3 日
Hi Sean, Your solution does work and is superior to mine.
thanks,
Pat.

サインインしてコメントする。

その他の回答 (1 件)

Cedric
Cedric 2014 年 7 月 3 日
編集済み: Cedric 2014 年 7 月 3 日
The following should be quite fast (faster than STR2DOUBLE for example):
flag = ~isempty( sscanf( x, '%f' )) ;
EDIT: if characters can appear only at the end of the string, the following will be very fast
flag = x(end) >= '0' && x(end) <='9'
  6 件のコメント
Cedric
Cedric 2014 年 7 月 4 日
編集済み: Cedric 2014 年 7 月 4 日
Can these numbers be floating point or are they integers only? Can they be negative?
Most important, do you really need to optimize further than STR2DOUBLE? The latter is certainly the most straightforward approach; most alternatives would be tricks based on some assumption(s).
For example, if you are only dealing with positive integers, the following will be quite fast
flag = all(x >= '0') && all(x <= '9') ;
Patrick Mboma
Patrick Mboma 2014 年 7 月 4 日
Thanks Cedric, in principle, the strings can be anything: floats, negative numbers, complex, etc. The bottom line is that if a string can be evaluated to give a double, then I separate it from the rest. In that case, although str2double goes through lots of checks, it seems superior to what I did earlier

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by