23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Variables<br />

Creating Global Variables. Each function that uses a global variable<br />

must first declare the variable as global. It is usually best to put global<br />

declarations toward the beginning of the function. You would declare global<br />

variable MAXLEN as follows:<br />

global MAXLEN<br />

If the M-file contains subfunctions as well, then each subfunction requiring<br />

access to the global variable must declare it as global. To access the variable<br />

from the <strong>MATLAB</strong> command line, you must declare it as global at the<br />

command line.<br />

<strong>MATLAB</strong> global variable names are typically longer and more descriptive<br />

than local variable names, and often consist of all uppercase characters. These<br />

are not requirements, but guidelines to increase the readability of <strong>MATLAB</strong><br />

code, and to reduce the chance of accidentally redefining a global variable.<br />

Displaying Global Variables. To see only those variables you have declared<br />

as global, use the who or whos functions with the literal, global.<br />

global MAXLEN MAXWID<br />

MAXLEN = 36; MAXWID = 78;<br />

len = 5; wid = 21;<br />

whos global<br />

Name Size Bytes Class<br />

MAXLEN 1x1 8 double array (global)<br />

MAXWID 1x1 8 double array (global)<br />

Grand total is 2 elements using 16 bytes<br />

Suggestions for Using Global Variables. A certain amount of risk is<br />

associated with using global variables and, because of this, it is recommended<br />

that you use them sparingly. You might, for example, unintentionally give<br />

a global variable in one function a name that is already used for a global<br />

variable in another function. When you run your application, one function<br />

may overwrite the variable used by the other. This error can be difficult to<br />

track down.<br />

3-5

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!