Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to force a user to input an integer in Matlab

Tags:

matlab

I'm writing a simple program in Matlab and am wondering the best way to ensure that the value a user is inputting is a proper integer.

I'm currently using this:

while((num_dice < 1) || isempty(num_dice))
    num_dice = input('Enter the number of dice to roll: ');
end

However I really know there must be a better way, because this doesn't work all the time. I would also like to add error checking ala a try catch block. I'm brand new to Matlab so any input on this would be great.

EDIT2:

try
    while(~isinteger(num_dice) || (num_dice < 1))
        num_dice = sscanf(input('Enter the number of dice to roll: ', 's'), '%d');
    end

    while(~isinteger(faces) || (faces < 1))
        faces = sscanf(input('Enter the number of faces each die has: ', 's'), '%d');
    end

    while(~isinteger(rolls) || (rolls < 1))
        rolls = sscanf(input('Enter the number of trials: ', 's'), '%d');
    end
catch
    disp('Invalid number!')
end

This seems to be working. Is there anything noticeably wrong with this? isinteger is defined by the accepted answer

like image 555
Tanner Avatar asked Mar 08 '11 18:03

Tanner


2 Answers

The following can be used directly in your code and checks against non-integer input including empty, infinite and imaginary values:

isInteger = ~isempty(num_dice) ...
            && isnumeric(num_dice) ...
            && isreal(num_dice) ...
            && isfinite(num_dice) ...
            && (num_dice == fix(num_dice));

The above will only work correctly for scalar input. To test whether a multi-dimensional array contains only integers you can use:

isInteger = ~isempty(x) ...
            && isnumeric(x) ...
            && isreal(x) ...
            && all(isfinite(x)) ...
            && all(x == fix(x))

EDIT

These test for any integer values. To restrict the valid values to positive integers add a num_dice > 0 as in @MajorApus's answer.

You can use the above to force the user to input an integer by looping until they succumb to your demands:

while ~(~isempty(num_dice) ...
            && isnumeric(num_dice) ...
            && isreal(num_dice) ...
            && isfinite(num_dice) ...
            && (num_dice == fix(num_dice)) ...
            && (num_dice > 0))
    num_dice = input('Enter the number of dice to roll: ');
end
like image 71
b3. Avatar answered Nov 12 '22 17:11

b3.


Try this, modify it as needed.

function answer = isint(n)

if size(n) == [1 1]
    answer = isreal(n) && isnumeric(n) && round(n) == n &&  n >0;
else
    answer = false;
end
like image 23
Miebster Avatar answered Nov 12 '22 16:11

Miebster