Function Matlab图形用户界面重用功能块
我在指南中制作了一个MatlabGUI,其中包含两个可编辑文本框和四个静态文本框 用户在两个可编辑文本框(Function Matlab图形用户界面重用功能块,function,matlab,matlab-guide,Function,Matlab,Matlab Guide,我在指南中制作了一个MatlabGUI,其中包含两个可编辑文本框和四个静态文本框 用户在两个可编辑文本框(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) % h
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
是否可以引用此代码块(包含在代码块中),以便功能e2\u按键FCN
也可以使用它?
现在我只想将该部分复制粘贴到
函数e2\u KeyPressFcn
,但这似乎不是很优雅。为您的代码块创建一个助手函数怎么样
我的想法是这样的:
function e1_KeyPressFcn(hObject, eventdata, handles)
handles = helper_block_func(handles);
function e2_KeyPressFcn(hObject, eventdata, handles)
handles = helper_block_func(handles);
function hout = helper_block_func(hin)
hout = hin;
% # Get values from e1 and e2 and calculate other values
hout.levels = str2num(get(hout.e1, 'String'));
hout.edgelength = str2num(get(hout.e2, 'String'));
hout.cellnum = (hout.levels ^ 3 + 3 * hout.levels ^ 2 + 2 * hout.levels) / 6;
hout.vertnum = ((hout.levels + 1) ^ 3 + 3 * (hout.levels + 1) ^ 2 ...
+ 2 * (hout.levels + 1)) / 6
% # Set values of s1, s2, s3 and s4
set(hout.s1, 'String', num2str(hout.cellnum));
set(hout.s2, 'String', num2str(hout.vertnum));
set(hout.s3, 'String', num2str(0.433 * hout.edgelength ^ 2));
set(hout.s4, 'String', ...
num2str(2 * hout.cellnum * str2num(get(hout.s3, 'String'))));
为什么不把所有的代码放在新函数中,当e1或e2发生变化时调用该函数呢?我可以把函数
hout
放在一个单独的文件中吗?我现在试过了,但不起作用。我应该使用一些特殊的命名吗?@BartArondson我调用了helper函数helper\u block\u func
hout
不是函数名,而是该函数中的局部变量。是的,当然可以将其放在单独的m文件中,只需确保文件的名称与函数的名称相同(例如“helper\u block\u func.m”)