MATLAB: How can i add a error check to this program such that the input must only be in numbers

matlab errorchecks

I want to add error checks to this program such that the 'value' input must only be in numbers and the program must keep asking the user for input until the user enters valid number instead of letters or symbols for 'value'.
x=input('choose between 1 to 3')
value = input('Enter any value that you want to convert:','s');
switch x
case 1
result= value+20
case 2
result=value+30
case 3
result=value+70
otherwise
end

Best Answer

Try this:
x=input('choose between 1 to 3')
while true
value = input('Enter any value that you want to convert:','s');
if ~isnan(str2double(value))
value=str2double(value);
break;
else
errordlg('Wrong type of value entered. Try again.');
end
end
switch x
case 1
result= value+20
case 2
result=value+30
case 3
result=value+70
otherwise
end
The key code is
~isnan(str2double(value))
This converts the value variable to double and isnan function checks whether the conversion resulted in NaN or numeric variable. According to that, the while loop is broken.