MATLAB Answers

0

how to create an error message when invalid data is input and then prompt to re-enter the data

person_age = input('Please enter persons age')
If person_age < 1
errordlg('Please input valid number','Error')
end
How do I display this error message and then prompt the user to re-enter the person_age?
Many thanks

  0 Comments

Sign in to comment.

Products


Release

R2017b

2 Answers

Answer by JESUS DAVID ARIZA ROYETH on 14 Nov 2019
 Accepted Answer

person_age = input('Please enter persons age');
while person_age < 1
errordlg('Please input valid number','Error')
person_age = input('Please enter persons age');
end

  4 Comments

Show 1 older comment
person_age = input('Please enter persons age');
errors={'Please input valid number >1','Please input valid number <=120'};
while person_age < 1 || person_age>120
errordlg(errors([person_age < 1 person_age>120]) ,'Error')
person_age = input('Please enter persons age');
end
thank you worked perfectly. Another question how would i say 'only accept the ages 10, 20 or 30' any other number input is invalid, show error message like above
person_age = input('Please enter persons age');
errors={'Please input valid number >1','Please input valid number <=120'};
while person_age < 1 || person_age>120
errordlg(errors([person_age < 1 person_age>120]) ,'Error')
person_age = input('Please enter persons age');
end
values=[10 20 30];
if ~ismember(person_age,values)
error(['only accept the ages ' num2str(values,'%i ')])
end

Sign in to comment.


Answer by Guillaume
on 14 Nov 2019

Typical pattern for this is:
value = someinvalidvalue;
while valueisinvalid
value = input('Enter value');
end
Note that your test is extremely incomplete. Any of the following inputs would be considered valid age:
  • NaN
  • [-1, 2]
  • Inf
  • 'abcdef'
  • 5 + 1i*2
You may want to change your test to:
while isnumeric(person_age) || isscalar(person_age) || isreal(person_age) || isfinite(person_age) || person_age < 1

  1 Comment

Many thanks for response, it is a simple machine learning database I am being assesed on, I dont think it requires that level of detail.

Sign in to comment.