我认为@chappjc 提供的选项是获得价值的最佳方式。我建议使用setappdata 和getappdata 的另一种可能对您有帮助的方法。它们用于将变量存储在某些工作区(例如基础工作区或特定函数的工作区)中,并可用于在函数之间共享数据。在此示例中,我使用 Matlab 根,即“基础”工作区。
在下面的代码中有2个函数,一个叫ABCFunction,计算d,一个叫ABCGUI,是一个简单的GUI来演示这一点。基本上用户在 3 个编辑文本框中输入 3 个值,按下按钮后,通过函数 'ABCFunction' 计算 d,并在编辑框中显示输出。
chappjc 提出的方法称为选项 A,使用 setappdata/getappdata 的选项称为选项 B。您可以在这两个函数中注释相应的代码来玩转,看看它是如何工作的。结果是一样的。所以他们在这里:
1)ABC函数
function d = ABCFunction(a,b,c)
%// Option A
d = a*b+c;
%//Option B
d = a*b+c; %// Does not change from Option A.
setappdata(0,'dInFunction',d); %// Assign the result, d, in a variable that you will call from your main GUI. See below.
end
2) ABCGui函数
function ABCGui(~)
% Create the GUI figure.
handles.figure = figure('Visible','on','Position',[360,500,300,285]);
handles.texta = uicontrol('Style','text','String','Enter a',...
'Position',[50,140,60,15]);
handles.edita = uicontrol('Style','edit','String','',...
'Position',[50,120,60,20]);
handles.textb = uicontrol('Style','text','String','Enter b',...
'Position',[120,140,60,15]);
handles.editb = uicontrol('Style','edit','String','',...
'Position',[120,120,60,20]);
handles.textc = uicontrol('Style','text','String','Enter c',...
'Position',[190,140,60,15]);
handles.editc = uicontrol('Style','edit','String','',...
'Position',[180,120,60,20]);
handles.Button = uicontrol('Style','pushbutton','String','Calculate d','Position',[50,60,80,15],'Callback',@PushbuttonCallback);
handles.textd = uicontrol('Style','text','String','d = a*b+c',...
'Position',[80,90,80,15]);
handles.textResult = uicontrol('Style','text','String','',...
'Position',[175,90,60,15]);
guidata(handles.figure,handles) %// Update handles structure.
%============================================================
%// Setup callback of the pushbutton
function PushbuttonCallback(~,~)
handles = guidata(gcf); %// Retrieve handles structure
A = str2num(get(handles.edita,'String'));
B = str2num(get(handles.editb,'String'));
C = str2num(get(handles.editc,'String'));
%// Option A
d = ABCFunction(A,B,C); %// Call the function and assign the output directly to a variable.
%// Option B
ABCFunction(A,B,C); %// Call the function and fetch the variable using getappdata.
d = getappdata(0,'dInFunction');
set(handles.textResult,'String',num2str(d));
end
end
图形用户界面非常简单,如下所示:
如您所见,将变量分配给函数输出要简单得多。如果不可能,您可以选择选项 B。希望对您有所帮助!