What is the most correct way of determining whether variable contains a number

16 ビュー (過去 30 日間)
Leos Pohl
Leos Pohl 2021 年 7 月 28 日
編集済み: Stephen23 2021 年 7 月 28 日
From what i have read, isnumeric is useless since eg. nan returns numeric output. Some answers mention to use str2double but str2double(2) returns NaN as does str2double("a"). So is there a universal function that is capable to eat both strings and numbers and tell you whether the string is a number (and if supplied with a number obviously returns true as well)?

回答 (3 件)

Chunru
Chunru 2021 年 7 月 28 日
It seems that you have to write your own function:
[t, f] = isstranum(5)
t = logical
1
f = 5
[t, f] = isstranum('nan')
t = logical
1
f = NaN
[t, f] = isstranum('-512.3')
t = logical
1
f = -512.3000
[t, f] = isstranum('abc')
t = logical
0
f = []
function [tf, y] = isstranum(x)
if isnumeric(x)
tf = true;
y = x;
elseif isstring(x) || ischar(x)
if strcmpi(x, 'nan') || strcmpi(x, 'inf')
tf = true;
y = str2double(x);
else
y = str2double(x);
if isnan(y)
tf = false;
y = [];
else
tf = true;
end
end
else
tf = false;
y = [];
end
end

Image Analyst
Image Analyst 2021 年 7 月 28 日
You can use isempty() to determine if a variable has any variable of any class whatsoever in it:
if isempty(yourVariable)
fprintf('yourVariable has nothing in it.\n')
else
fprintf('yourVariable has something in it.\n')
end
You might also take a look at exist(yourVariable, 'var') to see if a variable by that name even exists at all (empty or not).

Stephen23
Stephen23 2021 年 7 月 28 日
編集済み: Stephen23 2021 年 7 月 28 日
Let MATLAB do the heavy lifting for you:
fun = @(x) isnumeric(x)&&isfinite(x) || isfinite(str2double(x));
fun(2.3)
ans = logical
1
fun(NaN)
ans = logical
0
fun('2.3')
ans = logical
1
fun('NaN')
ans = logical
0
fun('abc')
ans = logical
0

カテゴリ

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

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by