23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3 Basic Program Components<br />

Another problem comes when you want to change the variable name. To<br />

make a change without introducing an error into the application, you must<br />

find every occurrence of that name in your code (and other people’s code, if<br />

you share functions).<br />

Alternatives to Using Global Variables. Instead of using a global<br />

variable, you may be able to<br />

• Pass the variable to other functions as an additional argument. In this way,<br />

you make sure that any shared access to the variable is intentional.<br />

If this means that you have to pass a number of additional variables,<br />

you can put them into a structure or cell array and just pass it as one<br />

additional argument.<br />

• Use a persistent variable (described in the next section), if you only need to<br />

make the variable persist in memory from one function call to the next.<br />

Persistent Variables<br />

Characteristics of persistent variables are<br />

• You can declare and use them within M-file functions only.<br />

• Only the function in which the variables are declared is allowed access to it.<br />

• <strong>MATLAB</strong> does not clear them from memory when the function exits, so<br />

their value is retained from one function call to the next.<br />

You must declare persistent variables before you can use them in a function.<br />

It is usually best to put your persistent declarations toward the beginning of<br />

the function. You would declare persistent variable SUM_X as follows:<br />

persistent SUM_X<br />

If you clear a function that defines a persistent variable (i.e., using clear<br />

functionname or clear all), or if you edit the M-file for that function,<br />

<strong>MATLAB</strong> clears all persistent variables used in that function.<br />

You can use the mlock function to keep an M-file from being cleared from<br />

memory, thus keeping persistent variables in the M-file from being cleared<br />

as well.<br />

3-6

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

Saved successfully!

Ooh no, something went wrong!