gpt4 book ai didi

function - Matlab GUI 重用功能 block

转载 作者:太空宇宙 更新时间:2023-11-03 20:05:10 25 4
gpt4 key购买 nike

我在 GUIDE 中制作了一个 Matlab GUI,其中包含两个可编辑文本框和四个静态文本框用户在两个可编辑文本框(e1e2)中输入值,并根据这些值计算应显示在静态文本框(s1s2s3s4)。

它在 e1e2 的每次值更改时执行此操作

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 但这似乎不是很优雅。

最佳答案

为您的代码块制作一个辅助函数怎么样?

我的想法是这样的:

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'))));

关于function - Matlab GUI 重用功能 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13934030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com