MATLAB: How to validate user input between 2 values

MATLABvalidating user input

i making a small function that asks the user to give 5 number so it calculates the average of it.
How do i keep the user from putting invalid values, say i want only values between 1 and 100 to count and reask the user if input wrong
as of now i have this
number1 = input('first number: ') %this 4 more times but +1 ofcourse
average = number1+.. /5;
disp('average is: ')
disp(average)
now if the user input is 0 or 101 or 500 something out of boundaries how do i ask the user to put in a valid number?
say number 1 is correct and user get prompt number 2 but types invalid number how do i reask it.
i've googled a bit but most answers dont fit my way.
thanks in advance!

Best Answer

" %this 4 more times but +1 ofcourse". When you have to repeat the same instruction more than once, you should be thinking loop. A for loop is ideal. In addition, that means you only have to write the validation code once.
Similarly, to reprompt the user if the input is not valid you can use a loop. A while loop is ideal for that. While the input is not valid, prompt.
The validation check itself can be done with if
So your algorithm should be:
for loop to count the input number
set a variable (e.g. validinput) to false, to indicate that the input is not yet valid
while input is not valid
prompt user for number, sprintf can help you build the prompt
put number into a vector using the input number as index
if input is valid (see my comment to adam)
set variable to true to indicate that input is valid
end
end
end
calculate mean of input vector
Related Question