Programming Fundamentals - The MathWorks - #251

/ 840


catalogue search
P. 251
P. 252
P. 253
P. 254
P. 255
P. 256
P. 257
P. 258
P. 259
P. 260
P. 261
P. 262
P. 263
P. 264
P. 265
P. 266
P. 267
P. 268
P. 269
P. 270
P. 271
P. 272
P. 273
P. 274
P. 275
P. 276
P. 277
P. 278
P. 279
P. 280
P. 281
P. 282
P. 283
P. 284
P. 285
P. 286
P. 287
P. 288
P. 289
P. 290
P. 291
P. 292
P. 293
P. 294
P. 295
P. 296
P. 297
P. 298
P. 299
P. 300


See other catalogues for The MathWorks

Text version of the page
Variables
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.
3-9

pageCatalog pdf di En 2012-06-22-01