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 />

Guidelines to Using Variables<br />

Thesameguidelines that apply to <strong>MATLAB</strong> variables at the command line<br />

also apply to variables in M-files:<br />

• You do not need to type or declare variables used in M-files (with the<br />

possible exception of designating them as global or persistent).<br />

• Before assigning one variable to another, you must be sure that the variable<br />

on the right-hand side of the assignment has a value.<br />

• Any operation that assigns a value to a variable creates the variable, if<br />

needed, or overwrites its current value, if it already exists.<br />

Scope of a Variable<br />

<strong>MATLAB</strong> stores variables in a part of memory called a workspace. The base<br />

workspace holds variables created during your interactive <strong>MATLAB</strong> session<br />

and also any variables created by running M-file scripts. Variables created at<br />

the <strong>MATLAB</strong> command prompt can also be used by scripts without having to<br />

declare them as global.<br />

Functions do notusethebaseworkspace. Everyfunctionhasitsown<br />

function workspace. Each function workspace is kept separate from the base<br />

workspace and all other workspaces to protect the integrity of the data used<br />

by that function. Even subfunctions that are defined in the same M-file have<br />

aseparatefunction workspace.<br />

Extending Variable Scope<br />

In most cases, variables created within a function are known only within that<br />

function. These variables are not available at the <strong>MATLAB</strong> command prompt<br />

or to any other function or subfunction.<br />

Passing Variables from Another Workspace. The most secure way to<br />

extend the scope of a function variable is to pass it to other functions as an<br />

argument in the function call. Since <strong>MATLAB</strong> passes data only by value,<br />

you also need to add the variable to the return values of any function that<br />

modifies its value.<br />

3-11

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

Saved successfully!

Ooh no, something went wrong!