Adam Merckx
Adam Merckx

Reputation: 1214

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

How can I call it?

magE = matrix of 244 rows and 2000 Columns

I would be grateful for any help. Thank you!

Upvotes: 0

Views: 985

Answers (2)

Nino Pereira
Nino Pereira

Reputation: 71

One way would be to declare magE as a global variable in the main script. Then, inside each function you should also declare it as global so that it would refer to the same global variable.

e.g.

global magE
<your_code_here>

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

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

Upvotes: 1

tuna_fish
tuna_fish

Reputation: 427

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. Example taken from 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)

Suppose you needed to access the numberOfErrors field in a push button callback. 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)

Upvotes: 1

Related Questions