How can I test if an input value is an integer?
Afficher commentaires plus anciens
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?
Réponse acceptée
Plus de réponses (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
Hung Chu
le 21 Fév 2017
1 vote
Adam
le 21 Fév 2017
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
le 3 Juil 2019
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 commentaire
Cris Luengo
le 9 Juil 2020
This does not work if the input is 0.
What is wrong with the other answers? They actually work!
Weimin Zhang
le 23 Fév 2023
0 votes
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
Catégories
En savoir plus sur Numeric Types dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!