How do I make an if-statement execute only if the value is an integer?

1 view (last 30 days)
This is the question: The pythagorean theorem states that a^2+b^2=c^2. Write a MATLAB program that finds all the combinations of triples a, b, and that are positive integers all smaller or equal to 50 that satisfy the Pythagorean theorem. Display the results in a three-column table in which every row corresponds to one triple. The first three rows of the table are:
3 4 5
5 12 13
6 8 10
What I've come up with is:
for a=1:1:50
for b=1:1:50
c=sqrt(a^2+b^2);
if (c<=50)
??????????????????????
fprintf('%3i %3i %3i\n', a, b, c)
end
b=b+1;
end
end
I know something needs to go where the question marks are in order to determine whether c is an integer...I just don't know what!

Answers (2)

Geoff Hayes
Geoff Hayes on 5 Nov 2014
Edited: Geoff Hayes on 5 Nov 2014
Hayley - you could try using the floor or ceil functions. For example, if we assume that c is a number (so not NaN or Inf) then
c<=50 && c==floor(c)
would be a sufficient condition for your if statement.

Adam
Adam on 5 Nov 2014
I have a utility function for this since it is something I have needed on a couple of occasions:
function valIsInt = isIntegerValued( val )
validateattributes( val, { 'single', 'double' }, { 'nonempty' } )
tolerance = 1e-10;
if isa( val, 'single' )
tolerance = 1e-5;
end
valIsInt = ( abs( round( val ) - val ) ) <= tolerance;
end
Obviously you can set tolerance to whatever you want, but that works for my purposes.

Tags

Community Treasure Hunt

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

Start Hunting!