Tag Archives: variable

Matlab variable sharing (global variable and such and such…)

Coming from another programming language (Delphi/C#), the one puzzled me about programming in Matlab is how do I share my variable just like I programmed desktop application using Delphi or C#.

After reading the documentation and a lot of forum browsing, finally I made up my mind and conclude my own “best-practice” when I want to share (global) variables in Matlab. (This is applied when we are developing a Matlab GUI via GUIDE).

Sharing variables between functions in one Form/GUI

  • use guidata and handles.

create a global variable that will be known by all functions inside a form/GUI

handles.my_global_var=[1 3 4 2 7]; % just a dummy matrix
guidata(hObject, handles);

recall/access that global variable within other function (still in the same form)


caveat: all global variables is destroyed when you close the Form/GUI


Sharing variables between multiple Forms/GUI but in one application

  • use setappdata and getappdata

create a global variable

setappdata(0, 'my_global_var', the_value);

accessing it

local_var=getappdata(0, 'my_global_var');

checking it (if it’s already set or not)

if (isappdata(0, 'my_global_var'))
    % my_global_var is already set, do something
    % my_global_var isn't there, warn user

deleting it

rmappdata(0, 'my_global_var');

caveat: variables is gone when you close Matlab; you can’t see the variables within Matlab Workspace


The highest level: sharing between multiple Forms/GUI and also with your Matlab Workspace/Command Window

  • use assignin and evalin


assignin('base', 'variable_name', the_value);


local_var=evalin('base', 'variable_name');

See the variables in your Matlab Workspace so you can analyze the variable further (maybe via Variable editor or directly via Command Window)

matlab workspace window

Matlab workspace window showing global variable

caveat: variables is gone when Matlab is closed

If you want to create variables that will not gone even after Matlab closed, you can use save and load command. Checkout Matlab Help page for further documentation about save and load.