Invalidate user entry by using isnan or isempty function

8 views (last 30 days)
Hi,
How do I invalidate a user entry if a positive number is required from the user but the user type a char or negative value.
when a user type a char or negative value,
a prompt will ask the user to reenter again.
% Check for erroneous input and prompt the user to enter option again
while conversion == 0
conv =str2double(conversion);
conversion = input("\nEnter an option. Yes or No \n", 's');
if isempty(conversion)
fprintf("Option Invalid");
conversion = input("\nEnter an option. DR or RD\n", 's');
elseif isnan(conv)
fprintf("Option Invalid");
conversion = input("Enter an option. DR or RD\n", 's');
elseif conv < 0
fprintf("Option Invalid");
conversion = input("Enter an option. DR or RD\n", 's');
end
end

Answers (1)

Jorg Woehl
Jorg Woehl on 8 Mar 2021
Edited: Jorg Woehl on 10 Mar 2021
str2double returns NaN (not-a-number) when it cannot convert text to a number. You can therefore simply use isnan to test if a number has been entered, and combine that with a x>0 check:
str = input('Enter an option: ', 's');
x = str2double(str);
while isnan(x) || ~(x>0)
str = input('Invalid input. Enter an option: ', 's');
x = str2double(str);
end

Categories

Find more on Numeric Types 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!