how can I check if a specific value in a matrix is an integer?

33 views (last 30 days)
Seba.V on 6 Aug 2019
Commented: Adam Danz on 7 Aug 2019
for i=14:20
A=[1 1 1; 10 6 2;0 1 0];
B=[50; 360; i];
if y/round(y)==1 && x/round(x)
fprintf('%3g & %3g integers\n',y,x)
fprintf('%3g & %3g not intigers\n',y,x)
by input different values of i am trying to see if the values of x and y are integers.
The output from the following code gives me the correct answer only to the first integer value checked and then fails all others.
How do I make the loop continue to check correctly on the other values generated?
Adam Danz
Adam Danz on 6 Aug 2019
Note that isinteger() detects values that are of the integer class such as int8, int16, int32, int64, uint8, uint16, uint32, and uint64. It does not test that a value is an integer (example below).
ans =

Sign in to comment.

Answers (2)

Adam Danz
Adam Danz on 6 Aug 2019
Edited: Adam Danz on 6 Aug 2019
There are better ways to test for integers. Your method is susceptible to round-off error. It also appears that you forgot the "==1" following round(x) which is why it's not working. Instead, use this method to test for intergers.
if mod(y,1) == 0 && mod(x,1) == 0
% or
if all(mod([x,y],1) == 0)
I also suggest changing the fprintf() commands so you can see many more decimal places.
fprintf('%.20f & %.20f not integers\n',y,x)

Sign in to comment.

Andreas Bernatzky
Andreas Bernatzky on 6 Aug 2019
Edited: Andreas Bernatzky on 6 Aug 2019
I am not quiet sure if you mean a REAL integer or just a number like 3. Because matlab stores everything as double by default. But in your code you just use "default" numbers (double for matlab). So your questions does not make really sense to me but i interpret that you will just check for example if a number is 14.0 or 14.3 (as example).
If you mean real integer here is a exemple:
TF = isinteger(int8(2))
Classical approach for your problem: modulo-operator or as in matlab mod(number2check,divisor)
myNumber = 3;
rest = mod(myNumber,1); % myNumber /1
%if you can divide a number by 1 and it got no rest -> "integer"
if(rest ==0) %means it is an "integer"
disp('hey I am an integer');
disp('hey I am not an integer');
Especially for your example:
Vector2Check = [13,41,21.5,43,11.5]; % vector which includes all your number which shall get checked
rest = mod(Vector2Check(a),1);
if(rest ==0) %means it is an "integer"
disp('hey I am an integer');
disp('hey I am not an integer');
Hope I haven't completely misunderstood your question and I could help

Community Treasure Hunt

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

Start Hunting!

Translated by