MATLAB: How to limit the range of numbers that can be entered into a MATLAB GUI text box

boxcapforcegraphicshandlehginputlimitMATLABrangetext;uicontrol

I have created a GUI in MATLAB that contains a text box control. I would like to limit the range of inputs to a number between 1 and 100.

Best Answer

To constrain the input to a MATLAB GUI text box, you must develop code to check the input and update the text box accordingly.
To limit the range of input to a number between 1 and 100, you can incorporate the following code in the callback function of the text box. Please note that the code can be used with text boxes that contain strings or cell arrays.
x = get(hObject,'String'); % get text from handles structure
try
y = x{1}; % cell to string
z = str2num(strtok(y)); % string to number

catch
z = str2num(strtok(x)); % string to number
end
lower_limit = 1;
upper_limit = 100;
%Output equals value of z if z falls between the bounds set by lower_limit
%and upper_limit. Otherwise it is 0 or an empty array
output = z*(z < upper_limit)*(z > lower_limit);
%If z does not fall within the bounds set by the limit parameters or is an
%empty array
if isempty(output) | (~output)
%Set the output value to the limit value closest to z
output = lower_limit*(z < lower_limit) + upper_limit*(z > upper_limit);
%If there is no value in z, set the output value to the lower limit of
%the desired bounds
if isempty(output)
output = lower_limit;
end
%Create a message string and initiate a message box informing the user
%to enter a value within the limits of the defined range
str = sprintf('Enter a number between %d and %d', lower_limit, upper_limit);
msgbox(str);
end
%Set the value of the text box to the new value, which lies within the
%value range
set(hObject,'String',{num2str(output(1))});