MATLAB: How to determine if a string can be converted to a numerical value

string

For example, I have two strings, 'abc' and '123'. I want to process them differently. If it is '123', I would use str2num to convert it to a number for my operation. If it is 'abc', I would do some other operation. My question is how to write the sentence to detect which of them can be converted to a numerical value?
Thank you.

Best Answer

Determining whether a string represents a legal numeric value is fairly messy if you wish to accept complete exponential floating point sequence and yet detect all malformed numbers. By and large it is the decimal point that causes the most problems, as it is optional but when it appears there can be numbers before it and/or numbers after it, but it is not legal for it to appear without numbers. .0e-1 is legal, 0.e-1 is legal, 0.0e-1 is legal, but .e-1 is not. The work to recognize whether a number is legal or not is very nearly the same as the work to determine the value of the number.
If you want to accept numbers but not 'nan' or one of the infinities, then you can use (e.g.)
all(ismember(potentialnumber, '0123456789+-.eEdD'))
and if it is true then try the conversion, and if the conversion fails then or the test was false, it was a string. You can improve on this test, such as by pre-checking whether the number of exponent characters is at most 1.