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);
checking it (if it’s already set or not)
if (isappdata(0, 'my_global_var')) % my_global_var is already set, do something else % my_global_var isn't there, warn user end
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);
See the variables in your Matlab Workspace so you can analyze the variable further (maybe via Variable editor or directly via Command Window)
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.