MATLAB Answers


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

Asked by Leon
on 17 Oct 2019 at 21:16
Latest activity Answered by Matt J
on 18 Oct 2019 at 14:56
I have a column variable normally look like this:
Once in a while the column data will be like this, i.e., composed entiredly of strings that can be converted to numerical values.
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.


Typically I use str2double() instead of str2num. Try using that, and if it cannot convert it will return a NaN. You can then do a sweep removing the NaN with [ ] . The strings that can be converted will, and the ones that can't can be removed.
Cool. It works! I did not know there is a str2double() before.
Thank you so much.
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.

Sign in to comment.





2 Answers

Answer by Matt J
on 18 Oct 2019 at 0:22
 Accepted Answer



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.
Many thanks, Everyone, for your help!

Sign in to comment.

Answer by Matt J
on 18 Oct 2019 at 14:56

all(48<=yourMatrix(:) & yourMatrix(:)<=57)


Sign in to comment.