Integer check
960 次查看(过去 30 天)
显示 更早的评论
How can i do an integer check in matlab? Say i have a number, a = 1.5, how do i check if it is integer or not? i want to use an if statement:
if non_integer(a) == true
end
so i need to know what to use for "non_integer", which would return a true or false
1 个评论
Phani
2021-10-6
I think you can use rem function which throws out the remainder.
if(rem(a,1) ~=0) %checks if a is an integer with help of remainder
....
end
采纳的回答
Sean de Wolski
2011-9-21
floor(x)==x
3 个评论
Jukka Kaipala
2016-7-27
Like it should. Inf is not considered an integer, and the same goes for NaN.
更多回答(4 个)
Walter Roberson
2011-9-21
I suggest you think about floor(), ceil(), fix(), and round()
2 个评论
Walter Roberson
2016-11-2
NaN == 0 is false, so in each of those cases, the result of the test would be false, indicating that the values are not integers.
But if you tried the one above, floor(inf)==inf then the result would be true, seemingly indicating that it is an integer when it is not.
Fandi Bataineh
2019-2-2
编辑:Fandi Bataineh
2019-2-2
use
floor(x)==ceil(x)
this will be true only for integers
1 个评论
Sivyer Ge
2019-2-24
Actually this will not work for type 'char'. Do you know other way to identify the difference between char and integer?
Manuel Alcazar
2019-9-16
function [bool,idx] = isint(x)
% Check whether input is integer or not
% Inf and NaN are not integers
if ~isnumeric(x)
error('Input must be a numeric, not a %s.',class(x))
end
bool = (mod(x,1) == 0);
% bool = (round(x) == floor(x)); % Other approach. Fails with Inf and
% NaN.
idx = find(bool);
% Manolín Sept-2019
end
0 个评论
per isakson
2019-9-16
function isf = isflint( m )
% floating double only
%
% http://www.mathworks.com/company/newsletters/news_notes/pdf/Fall96Cleve.pdf
% JanSimon: http://www.mathworks.se/matlabcentral/answers/67247-about-isinteger- ...
% command-confusion#answer_78914
assert( isa( m, 'double' ) && isvector( m ) ...
, 'isflint:IllegalInput' ...
, 'The input should be a double vector' )
isf = all( abs( m ) <= flintmax ) ...
&& all( floor( m ) == m ) ;
end
1 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!