【发布时间】:2012-12-05 17:19:21
【问题描述】:
我在 GUIDE 中制作了一个带有两个可编辑文本框和四个静态文本框的 Matlab GUI
用户在两个可编辑文本框(e1 和 e2)中输入值,并根据这些值计算应在静态文本框中显示的值(s1、s2、s3 和s4)。
它在e1 和e2 的每个值更改时执行此操作
e1 更改值时计算值的代码如下所示。
% --- Executes on key press with focus on e1 and none of its controls.
function e1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to e1 (see GCBO)
% eventdata structure with the following fields (see UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% Start of BLOCK
% Get values from e1 and e2 and calculate other values
handles.levels = str2num(get(handles.e1, 'String'));
handles.edgelength = str2num(get(handles.e2, 'String'));
handles.cellnum = (handles.levels^3 + 3*handles.levels^2 + 2*handles.levels)/6;
handles.vertnum = ((handles.levels+1)^3 + 3*(handles.levels+1)^2 + 2*(handles.levels+1))/6;
% Set values of s1, s2, s3 and s4
set(handles.s1, 'String', num2str(handles.cellnum));
set(handles.s2, 'String', num2str(handles.vertnum));
set(handles.s3, 'String', num2str(0.433*handles.edgelength^2));
set(handles.s4, 'String', ...
num2str(2*handles.cellnum*str2num(get(handles.s3, 'String'))));
% End of BLOCK
是否可以引用此代码块(包含在 BLOCK 中)以便function e2_KeyPressFcn 也可以使用它?
现在我只需将该部分复制粘贴到function e2_KeyPressFcn,但这似乎不是很优雅。
【问题讨论】:
-
为什么不把所有的代码放在你的新函数中,当e1或e2发生变化时调用该函数?
标签: function matlab matlab-guide