How do global variables differ from regular (local) variables?
Each function in MATLAB contains a set of variables specific to that function. Even in the same .m file, you don’t have (direct) access to variables created in other functions within the file. Global variables give you the ability to create/change a variable in one function and have that updated variable accessible elsewhere. This post will discuss two methods for handling (no pun intended) global variables, one of which is perfectly integrated into Graphical User Interfaces (GUIs).
METHOD 1: global VARIABLE
The first (non-GUI) way to create a global variable is to use the function ‘global’. Create the global variables X, Y, and Z with the command:
global X Y Z
The ‘global’ function needs to be called in each separate function (usually in the beginning) where the variables will be called. Stylistically, the variable names are usually longer names and all in CAPS to indicate global variables within the functions. The documented example in the MATLAB helps shows this pretty well: