How can I use a while loop to check input for negative numbers and non-numerical input?

84 views (last 30 days)
Hi, I'm very new to matlab and my issue might be very simple, but I've been trying and failing to use a while loop to check an input. I tried to base it off of what I read in my textbook and a sample format, like this:
inputnum=input('Enter a positive number: ');
while inputnum>=0
fprintf('You entered a %d. \n\n', inputnum)
inputnum=input('Enter a positive number: ');
end
I have tried many variations and can't seem to get it to work. I just need to check that the input entered by the user is a number (not a character/string, and not negative), and have the script give them the option to enter the input again rather than just ending the program. How can I do this? Thanks.

Answers (2)

Image Analyst
Image Analyst on 11 Oct 2015
See this snippet:
% Ask user for two floating point numbers.
defaultValue = {'45.67', '78.91'};
titleBar = 'Enter a value';
userPrompt = {'Enter floating point number 1 : ', 'Enter floating point number 2: '};
caUserInput = inputdlg(userPrompt, titleBar, 1, defaultValue);
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue1 = str2double(caUserInput{1})
usersValue2 = str2double(caUserInput{2})
% Check for a valid number.
if isnan(usersValue1)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
% Convert the default from a string and stick that into usersValue1.
usersValue1 = str2double(defaultValue{1});
message = sprintf('I said it had to be a number.\nI will use %.2f and continue.', usersValue1);
uiwait(warndlg(message));
end

Tamir Suliman
Tamir Suliman on 7 Jan 2018
Edited: Tamir Suliman on 7 Jan 2018
inputnum=input('Enter a positive number: ');
while inputnum<0
fprintf('You entered a %d. \n\n', inputnum)
inputnum=input('Enter a positive number: ');
end
You only need to change the > sign to < the logic was just wrong
Enter a positive number: -1 You entered a -1.
Enter a positive number:

Categories

Find more on Language Fundamentals in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!