Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test for integers in MATLAB?

Tags:

integer

matlab

I'm writing a program that will calculate factorials of integers. However, the part I'm stuck on is if someone enters a non-integer such as 1.3, I'd like to be able to test the input and display "The number you have entered is not an integer"

like image 426
Ryan Avatar asked Mar 22 '11 19:03

Ryan


People also ask

How do you check if a number is an integer?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .

How do you check if a number is even in MATLAB?

To determine whether a number n is even or odd you can use the function rem(n,2). If rem(n,2) equals 0 then the number is even, otherwise it is odd. One nice thing about Matlab is that your program will work fine, no matter how inefficient you wrote it.


2 Answers

You can use the mod function, which returns the remainder after division. All integers are divisible by 1. So a good test for non-integer would be

integerTest=~mod(value,1);

This returns 0 if value is not an integer and 1 if it is. You can then use this as a conditional to reject non-integer user inputs.

like image 159
abcd Avatar answered Sep 24 '22 02:09

abcd


Here is another variation (you can see it being used in ISIND function: edit isind.m):

integerTest = ( x == floor(x) );

On my machine, it is faster than the other proposed solutions:

%# create a vector of doubles, containing integers and non-integers
x = (1:100000)';                       %'
idx = ( rand(size(x)) < 0.5 );
x(idx) = x(idx) + rand(sum(idx),1);

%# test for integers
tic, q1 = ~mod(x, 1); toc
tic, q2 = x==double(uint64(x)); toc
tic, q3 = x==floor(x); toc

%# compare results
assert( isequal(q1,q2,q3) )

Timings:

Elapsed time is 0.012253 seconds.
Elapsed time is 0.014201 seconds.
Elapsed time is 0.005665 seconds.
like image 24
Amro Avatar answered Sep 27 '22 02:09

Amro