How to determine if a string can be converted to a numerical value?
Mostra commenti meno recenti
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.
Risposta accettata
Più risposte (3)
Kaustubha Govind
il 23 Mar 2011
[num, status] = str2num(str)
status=0 if conversion is not successful, and 1 if it is.
4 Commenti
Matt Tearle
il 23 Mar 2011
Beat me to it. If status = 0, do your other operation on str.
Liqing
il 23 Mar 2011
Matt Tearle
il 23 Mar 2011
If you have a set of values you consider "missing", you don't have many options but to determine those by brute-force. But you might as well still do the conversion then test the result. Eg
num = str2num(str)
if (isempty(num) | ~isfinite(num) | (num==-999))
% not a valid number, do alternate thing
else
% number, go ahead
end
Florian Schwaiger
il 23 Feb 2015
Old thread but: you need to know that str2num uses eval internally. The following also passes this test:
>> [a, b] = str2num('SomeClassName')
a =
1x1 SomeClassName
b =
1
Alexander
il 26 Feb 2016
The following code will give you the output of str2double with an element-wise status output like str2num:
function [X,status] = MYstr2double(str)
X = str2double(str);
status = ~xor(strcmpi(strtrim(str),'NaN'),isnan(X));
end
This code works with in input that is a string or cell array of strings
Leon
il 4 Giu 2019
0 voti
Old thread, but the function 'isfloat" will do the trick.
Categorie
Scopri di più su Characters and Strings in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!