簡體   English   中英

如何在另一個函數中調用一個函數中使用的變量?

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

我已經創建了一個matlab gui,我想使用函數(pushbutton2)中的函數(pushbutton1)變量magE

我怎么稱呼它?

magE = matrix of 244 rows and 2000 Columns

我將不勝感激。 謝謝!

一種方法是在主腳本中將magE聲明為全局變量。 然后,在每個函數內部,還應將其聲明為全局變量,以便它引用相同的全局變量。

例如

global magE
<your_code_here>

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

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

您應該使用hObject句柄在GUI函數和回調之間傳遞數據,這在自動生成的注釋中已得到很好的解釋。 取自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)

假設您需要訪問按鈕回調中的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM