Programming Previous page   Next Page

Naming Variables

MATLAB variable names must begin with a letter, which may be followed by any combination of letters, digits, and underscores. MATLAB distinguishes between uppercase and lowercase characters, so A and a are not the same variable.

Although variable names can be of any length, MATLAB uses only the first N characters of the name, (where N is the number returned by the function namelengthmax), and ignores the rest. Hence, it is important to make each variable name unique in the first N characters to enable MATLAB to distinguish variables.

The genvarname function can be useful in creating variable names that are both valid and unique.

Verifying a Variable Name

You can use the isvarname function to make sure a name is valid before you use it. isvarname returns 1 if the name is valid, and 0 otherwise.

Avoid Using Function Names for Variables

When naming a variable, make sure you are not using a name that is already used as a function name. If you define a variable with a function name, you won't be able to call that function until you either remove the variable from memory with the clear function, or invoke the function using builtin.

For example, if you enter the following command, you will not be able to use the MATLAB disp function until you clear the variable with clear disp.

To test whether a proposed variable name is already used as a function name, use

Potential Conflict with Function Names.   There are some MATLAB functions (i and j, for instance) that have names that are commonly used as variable names in programming code. If you see a need to use a particular function name such as one of these for a variable, and you determine that you have no need to call that function in your program, you should be aware that there is still a possibility for conflict. See the following example.

The test_j function shown here loads data from MAT-file saved_data.mat and displays the value of the loaded variable j:

Prior to running the function, set j to a known value and save it to the MAT-file:

When you run the function, you get an unexpected answer. The value displayed for j shows that MATLAB has interpreted it as a function name, even though it seems that the load operation should have loaded it into the workspace as a variable:

Because MATLAB parses function files before they are run, it needs to determine before runtime which terms in the code are variables and which are functions. The function in this example does not establish j as a variable name (for example, by placing it to the left of an = sign) and, as a result, MATLAB interprets it as a function name.

There are at least two ways to make this function work as intended without having to change the variable name. Both indicate to MATLAB that the name represents a variable, and not a function:


Previous page  Variables Guidelines to Using Variables Next page

© 1994-2005 The MathWorks, Inc.