如何在另一个函数中调用一个函数中使用的变量?

时间:2016-04-12 08:09:59

标签: matlab matlab-guide

我创建了一个matlab gui,我想在函数(pushbutton2)中使用函数(pushbutton1)中的变量magE

我怎么称呼它?

magE = matrix of 244 rows and 2000 Columns

如果有任何帮助,我将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

一种方法是将magE声明为主脚本中的全局变量。 然后,在每个函数内部,您还应该将其声明为全局,以便它引用相同的全局变量。

e.g。

global magE
<your_code_here>

function [] = pushbutton1()
  global magE
  %%<your_code_here>
end

function [] = pushbutton2()
  global magE
  %%<your_code_here>
end

答案 1 :(得分:1)

你应该使用hObject句柄在GUI函数和回调之间传递数据,这一点在自动生成的注释中都得到了很好的解释。取自MATLAB documentation的示例:

% --- Executes just before simple_gui_tab is made visible.
function my_GUIDE_GUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to simple_gui_tab (see VARARGIN)
% ...
% add some additional data as a new field called numberOfErrors
handles.numberOfErrors = 0;
% Save the change you made to the structure guidata(hObject,handles)

假设您需要访问按钮回调中的numberOfErrors字段。您的回调代码现在看起来像这样:

% --- Executes on button press in pushbutton1.
function my_GUIDE_GUI_pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% ...
% No need to call guidata to obtain a structure;
% it is provided by GUIDE via the handles argument
handles.numberOfErrors = handles.numberOfErrors + 1;
% save the changes to the structure
guidata(hObject,handles)