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!