MATLAB: How to determine if cell contains only numbers

how to determine if cell contains only numbers

Hello MatLab-Pros,
I have a cell array where the cells are filled with either numbers(somtimes with +/-) or letters, but all of them are saved as string. If I convert it with str2double, the numbers get successfully convertet and the cells containing letters become NaN, as expected.
How can I check beforehand which cells contain letters, to copy them in a different array?
Thank you very much

Best Answer

It really depends on what you define a "number" to be:
  • negative?
  • complex?
  • exponent notation?
  • hexadecimal?
  • Inf or NaN?
  • etc
Each of these will change the definition of what a non-number is, and what characters are permitted in the number definitions. It is possible to specify regular expressions to identify different numbers types, but the first step is to precisely specify what format those numbers can be.
See my FEX submission natsort for lots of examples of regular expressions that identify different number formats and types:
Assuming that you are happy with the numbers that str2double identifies then one very simple method is to convert first, and separate second:
>> inp = {'1','Hello','3.1415','World'};
>> tmp = str2double(inp);
>> idx = isnan(tmp);
>> num = tmp(~idx)
num =
1.0000 3.1415
>> str = inp(idx);
>> str{:}
ans = Hello
ans = World
And if you expect NaNs as well use:
idx = isnan(tmp) & ~strcmpi('NaN',inp);
You are not likely to get a much simpler method than this simple application of str2double.