具有绘图显示参数的用 GUIDE 创建的 App
注意
在以后的版本中将会删除 GUIDE 环境。在删除 GUIDE 后,使用 GUIDE 创建的现有 App 可以继续在 MATLAB® 中运行,但不能在 GUIDE 中对其进行编辑。
要继续编辑使用 GUIDE 创建的现有 App,请参阅 GUIDE 迁移策略,了解有关如何帮助保持该 App 与未来 MATLAB 版本的兼容性的信息。要以交互方式创建新 App,请改用使用 App 设计工具开发 App。
此示例说明如何查看和运行一个预置的使用 GUIDE 创建的 App。该 App 包含三个编辑字段和两个坐标区。坐标区显示了一个函数(为两个正弦波之和)的频域和时域表示。上面的两个编辑字段包含每个正弦波分量的频率。第三个编辑字段包含绘图的时间范围和采样率。
打开并运行示例
打开并运行 App。更改 f1 和 f2 字段中的默认值,以更改每个正弦波分量的频率。也可以更改 t 字段中的三个数值(以冒号分隔)。第一个和最后一个数值指定对函数采样的时间窗口。中间的数值指定采样率。
按绘图按钮,以查看函数的频域和时域图。
查看代码
在 GUIDE 中,点击编辑器按钮 以查看代码。
在编辑器窗口靠近顶部的位置,使用 转至 按钮导航到下面讨论的函数。
f1_input_Callback
和 f2_input_Callback
f1_input_Callback
函数在用户更改 f1 编辑字段中的值时执行。f2_input_Callback
函数响应 f2 字段中的更改,它与 f1_input_Callback
函数几乎完全相同。两个函数都会检查用户输入是否有效。如果编辑字段中的值无效,则绘图按钮将被禁用。以下是 f1_input_Callback
函数的代码。
f1 = str2double(get(hObject,'String')); if isnan(f1) || ~isreal(f1) % 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
t_input_Callback
t_input_Callback
函数在用户更改 t 编辑字段中的值时执行。以下 try
代码块会检查该值,确保其为数值,长度介于 2 到 1000 之间,且该向量为单调递增。
try t = eval(get(handles.t_input,'String')); if ~isnumeric(t) % t is not a number set(handles.plot_button,'String','t is not numeric') elseif length(t) < 2 % t is not a vector set(handles.plot_button,'String','t must be vector') elseif length(t) > 1000 % t is too long a vector to plot clearly set(handles.plot_button,'String','t is too long') elseif min(diff(t)) < 0 % t is not monotonically increasing set(handles.plot_button,'String','t must increase') else % Enable the Plot button with its original name set(handles.plot_button,'String','Plot') set(handles.plot_button,'Enable','on') return end catch EM % Cannot evaluate expression user typed set(handles.plot_button,'String','Cannot plot t'); uicontrol(hObject); end
catch
代码块会更改绘图按钮上的标签,指示输入值无效。uicontrol
命令将焦点设为包含错误值的字段。plot_button_Callback
plot_button_Callback
函数在用户点击绘图按钮时执行。
首先,回调获取三个编辑字段中的值:
f1 = str2double(get(handles.f1_input,'String')); f2 = str2double(get(handles.f2_input,'String')); t = eval(get(handles.t_input,'String'));
f1
、f2
和 t
的值在时域内对函数进行采样,并计算傅里叶变换。之后,坐标区中的两幅绘图将被更新:
% Create frequency plot in proper axes plot(handles.frequency_axes,f,m(1:257)); set(handles.frequency_axes,'XMinorTick','on'); grid(handles.frequency_axes,'on'); % Create time plot in proper axes plot(handles.time_axes,t,x); set(handles.time_axes,'XMinorTick','on'); grid on