Check Variable Scope in Editor
In this section...
“Use Automatic Function and Variable Highlighting” on page 20-14
“Example of Using Automatic Function and Variable Highlighting” on page 20-14
Scoping issues can be the source of some coding problems. For instance, if you are unaware that
nested functions share a particular variable, the results of running your code might not be as you
expect. Similarly, mistakes in usage of local, global, and persistent variables can cause unexpected
results.
The Code Analyzer does not always indicate scoping issues because sharing a variable across
functions is not an error—it may be your intent. Use MATLAB function and variable highlighting
features to identify when and where your code uses functions and variables. If you have an active
Internet connection, you can watch the Variable and Function Highlighting video for an overview of
the major features.
For conceptual information on nested functions and the various types of MATLAB variables, see
“Sharing Variables Between Parent and Nested Functions” on page 20-28 and “Share Data Between
Workspaces” on page 20-10.
Use Automatic Function and Variable Highlighting
By default, the Editor indicates functions, local variables, and variables with shared scope in various
shades of blue. Variables with shared scope include: global variables on page 20-12, persistent
variables on page 20-11, and variables within nested functions. (For more information, see “Nested
Functions” on page 20-10.)
To enable and disable highlighting or to change the colors, click
Preferences and select
MATLAB > Colors > Programming tools. In MATLAB Online, highlighting is enabled by default
and changing the preferences for highlighting is not available.
By default, the Editor:
• Highlights all instances of a given function or local variable in sky blue when you place the cursor
within a function or variable name. For instance:
• Displays a variable with shared scope in teal blue, regardless of the cursor location. For instance:
Example of Using Automatic Function and Variable Highlighting
Consider the code for a function rowsum:
function rowTotals = rowsum
% Add the values in each row and
% store them in a new array
x = ones(2,10);
20 Function Basics
20-14
Précédent

- 722/1450

Suivant