# 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];
C=A^-1*B;
y=C(1,1);
x=C(3,1);
if y/round(y)==1 && x/round(x)
fprintf('%3g & %3g integers\n',y,x)
else
fprintf('%3g & %3g not intigers\n',y,x)
end
end
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?
##### 2 CommentsShowHide 1 older comment
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).
isinteger(1.0)
ans =
logical
0

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)
Adam Danz on 7 Aug 2019
@John D'Errico, I bet that'd be an interesting conversation!

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');
else
disp('hey I am not an integer');
end
Vector2Check = [13,41,21.5,43,11.5]; % vector which includes all your number which shall get checked
for(a=1:1:length(Vector2Check))
rest = mod(Vector2Check(a),1);
if(rest ==0) %means it is an "integer"
disp('hey I am an integer');
else
disp('hey I am not an integer');
end
end
Hope I haven't completely misunderstood your question and I could help
Greets
Andi