简体   繁体   English

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

[英]How to call a variable used in one function in another function?

I have created a matlab gui and I want to use the variable magE from the function (pushbutton1) in the function (pushbutton2). 我已经创建了一个matlab gui,我想使用函数(pushbutton2)中的函数(pushbutton1)变量magE

How can I call it? 我怎么称呼它?

magE = matrix of 244 rows and 2000 Columns

I would be grateful for any help. 我将不胜感激。 Thank you! 谢谢!

One way would be to declare magE as a global variable in the main script. 一种方法是在主脚本中将magE声明为全局变量。 Then, inside each function you should also declare it as global so that it would refer to the same global variable. 然后,在每个函数内部,还应将其声明为全局变量,以便它引用相同的全局变量。

eg 例如

global magE
<your_code_here>

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

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

You should be using the hObject handle to pass data between GUI functions and callbacks, it's all quite well explained in the auto-generated comments. 您应该使用hObject句柄在GUI函数和回调之间传递数据,这在自动生成的注释中已得到很好的解释。 Example taken from MATLAB documentation : 取自MATLAB文档的示例:

% --- 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)

Suppose you needed to access the numberOfErrors field in a push button callback. 假设您需要访问按钮回调中的numberOfErrors字段。 Your callback code now looks something like this: 您的回调代码现在看起来像这样:

% --- 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM