MATLAB Creating Graphical User Interfaces

(Barry) #1

9 Examples of GUIDE UIs


Validate Input as Numbers


When you UI displays, you can type parameters into three edit text fields as strings
of text. If you type an invalid value, the graphs can fail to inform or even to generate.
Preventing bad inputs from being processed is an important function of almost any UI
that performs computations. This UI code validates these inputs:


  • Ensure all three inputs are positive or negative real numbers

  • Ensures that the t (time) input is a vector that increases monotonically and is not too
    long to display


Validate all three inputs are positive or negative real numbers

In this example, each edit text control callback validates its input. If the input fails
validation, the callback disables the Plot button, changes its String to indicate the
type of problem encountered, and restores focus to the edit text control, highlighting
the erroneous input. When you enter a valid value, the Plot button reenables with its
String set back to 'Plot'. This approach prevents plotting errors and avoids the need
for an error dialog box.

The str2double function validates most cases, returning NaN (Not a Number) for
nonnumeric or nonscalar string expressions. An additional test using the isreal
function makes sure that a text edit field does not contain a complex number, such as
'4+2i'. The f1_input_Callback contains the following code to validate input for f1 :
function f1_input_Callback(hObject, eventdata, handles)
% Validate that the text in the f1 field converts to a real number
f1 = str2double(get(hObject,'String'));
if isnan(f1) || ~isreal(f1)
% isdouble returns NaN for non-numbers and f1 cannot be complex
% Disable the Plot button and change its string to say why
set(handles.plot_button,'String','Cannot plot f1')
set(handles.plot_button,'Enable','off')
% Give the edit text box focus so user can correct the error
uicontrol(hObject)
else
% Enable the Plot button with its original name
set(handles.plot_button,'String','Plot')
set(handles.plot_button,'Enable','on')
end
Similarly, f2_input_Callback code validates the f2 input.

Validate the Time Input Vector

The time vector input, t, is more complicated to validate. As the str2double function
does not operate on vectors, the eval function is called to convert the input string into
Free download pdf