How to check if an entire column of string variables can potentially be converted to numerical values?

1 回表示 (過去 30 日間)
I have a column variable normally look like this:
'ABC1234'
'DEC1236'
'CFG5645'
...
Once in a while the column data will be like this, i.e., composed entiredly of strings that can be converted to numerical values.
'1234567'
'2312456'
'7863522'
...
When this happens, I want to use str2num to convert them into numerical values first before using writetable to put them into an Excel file. Otherwise, I would see all those yellow diamonds with ! inside next to each row of the column to indicate errors.
So how do I detect if all elements in an entire column can potentially be converted to numerical values?
Also when I treid to use str2num, why am I getting the below error?
Input must be a character vector or string scalar.
  3 件のコメント
Leon
Leon 2019 年 10 月 17 日
Cool. It works! I did not know there is a str2double() before.
Thank you so much.
Guillaume
Guillaume 2019 年 10 月 17 日
編集済み: Guillaume 2019 年 10 月 17 日
As the documentation of str2num states, it's a dangerous function to use (internally it uses eval so I could give you a string that would delete everything on your hard drive were you to pass it to str2num.)
Whenever possible prefer str2double which is guaranteed to not have any side effect.

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

採用された回答

Matt J
Matt J 2019 年 10 月 18 日
~any(isletter(yourMatrix(:)))
  2 件のコメント
Guillaume
Guillaume 2019 年 10 月 18 日
Performing the conversion and checking for NaNs would be more reliable. The above would be happy with '------' which is of course not a valid number.
Leon
Leon 2019 年 10 月 18 日
編集済み: Leon 2019 年 10 月 18 日
Many thanks, Everyone, for your help!

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

その他の回答 (1 件)

Matt J
Matt J 2019 年 10 月 18 日
all(48<=yourMatrix(:) & yourMatrix(:)<=57)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by