Invalidate user entry by using isnan or isempty function

9 visualizzazioni (ultimi 30 giorni)
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

Risposte (1)

Jorg Woehl
Jorg Woehl il 8 Mar 2021
Modificato: Jorg Woehl il 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

Categorie

Scopri di più su Numeric Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by