| Creating Global Variables. Each function that uses a global variable must first declare the variable as global. It is usually best to put global declarations toward the beginning of the function. You would declare global variable MAXLEN as follows: global MAXLEN If the M-file contains subfunctions as well, then each subfunction requiring access to the global variable must declare it as global. To access the variable from the MATLAB command line, you must declare it as global at the command line. MATLAB global variable names are typically longer and more descriptive than local variable names, and often consist of all uppercase characters. These are not requirements, but guidelines to increase the readability ofMATLAB code, and to reduce the chance of accidentally redefining a global variable. Displaying Global Variables. To see only those variables you have declared as global, use the who or whos functions with the literal, global. global MAXLEN MAXWID MAXLEN = 36; MAXWID = 78; len = 5; wid = 21; whos global Name Size Bytes Class MAXLEN 1x1 8 double array (global) MAXWID 1x1 8 double array (global) Grand total is 2 elements using 16 bytes Suggestions for Using Global Variables. A certain amount ofrisk is associated with using global variables and, because ofthis, it is recommended that you use them sparingly. You might, for example, unintentionally give a global variable in one function a name that is already used for a global variable in another function. When you run your application, one function may overwrite the variable used by the other. This error can be difficult to track down. |