Wednesday, August 20, 2014

sharing global variables between function guide matlab



There might be a situation where you need to share variables between functions callback in matlab gui for example using variables which are initiated during gui start. There are 2 ways to do this

1. using global variable
function gui_OpeningFcn(hObject, eventdata, handles, varargin)
global x y z;
x = 1;
y = 2;
z = 3;

function pushbuttonNext_Callback(hObject, eventdata, handles)
global x y z;

x = x+1
y = y+1
z = z+1

function pushbuttonPrevious_Callback(hObject, eventdata, handles)
global x y z;

x = x-1
y = y-1
z = z-1

  2. using guidata
function gui_OpeningFcn(hObject, eventdata, handles, varargin)
x = 1;
y = 2;
z = 3;

handles.x = x;
handles.y = y;
handles.z = z;

guidata(hObject, handles);


function pushbuttonNext_Callback(hObject, eventdata, handles)
handles.x = handles.x + 1;
handles.y = handles.y + 1;
handles.z = handles.z + 1;

guidata(hObject,handles);

function pushbuttonPrevious_Callback(hObject, eventdata, handles)
handles.x = handles.x - 1;
handles.y = handles.y - 1;
handles.z = handles.z - 1;

guidata(hObject,handles);
*note that line 10, 18, 25 is called to save the variable in guidata structure so we are able to access in from other function scope

http://suki.noip.me/ifelse/sharing-global-variables-between-function-guide-matlab/

No comments:

Post a Comment