How can I test if an input value is an integer?
显示 更早的评论
I want to know how to test whether an input value is an integer or not. I have tried using the function isinteger, but I obtain, for example, isinteger(3) = 0. Apparently, any constant is double-precision by Matlab default, and is therefore not recognized as an integer. Can anyone tell me what function I'm supposed to use?
采纳的回答
更多回答(5 个)
assert(mod(x, 1) == 0, '%s: X must be an integer', mfilename);
Or safe this as M-file:
function T = isIntegerValue(X)
T = (mod(X, 1) == 0);
end
And then:
if ~isIntegerValue(X)
error('%s: X must be an integer', mfilename);
end
Adam
2017-2-21
I use e.g.
validateattributes( myInteger, { 'double' }, { 'scalar', 'integer' } )
for validating my input arguments. Not so useful if you want a boolean/logical returned though to do something with after, although you can catch the exception that gets thrown but its untidy and inefficient to do that.
randell mullally
2019-7-3
I needed the same thing. these answers are Blaah for me so here was my soloution.
clear;
clc;
A=[3.6,4,4.25,5,6.175,nan,inf];
SizeA=size(A);
B=zeros(SizeA);
for i=1:SizeA(1,2)
if A(i)/round(A(i))==1
B(i)=1;
end
end
AB=[A;B]
AB =
3.6000 4.0000 4.2500 5.0000 6.1750 NaN Inf
0 1.0000 0 1.0000 0 0 0
I suppose if you want to test just one at a time... and let y be the test subject.
y=5;
if y/round(y)==1
fprintf('%3g is an intiger!! hooray\n',y)
else
fprintf('%3g is not an intiger!! sorry\n',y)
end
5 is an intiger!! hooray
testing this with A yeilds good results.
clear;
clc;
A=[3.6,4,4.25,5,6.175,nan,inf];
SizeA=size(A);
B=zeros(SizeA);
for i=1:SizeA(1,2)
if A(i)/round(A(i))==1
B(i)=1;
end
y=A(i);
if y/round(y)==1
fprintf('%3g is an intiger!! hooray\n',y)
else
fprintf('%3g is not an intiger!! sorry\n',y)
end
end
AB=[A;B];
3.6 is not an intiger!! sorry
4 is an intiger!! hooray
4.25 is not an intiger!! sorry
5 is an intiger!! hooray
6.175 is not an intiger!! sorry
NaN is not an intiger!! sorry
Inf is not an intiger!! sorry
If you really really really like this, ALOT!
find me on linkedin and endorse my matlab skill.
Best of luck!
1 个评论
Cris Luengo
2020-7-9
This does not work if the input is 0.
What is wrong with the other answers? They actually work!
Weimin Zhang
2023-2-23
0 个投票
For an array x, perhaps use this:
assert(~any(mod(x,1)),'x must have integer(s) only');
or a function allIntegers = @(x)~any(mod(x,1))
For example,
>> allIntegers([1,2,3])
ans = logical 1
>> allIntegers([1,2.5,3])
ans = logical 0
类别
在 帮助中心 和 File Exchange 中查找有关 Variables 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!