Transparency in MATLAB Code
Code has transparent variable access if MATLAB® can identify every variable access by scanning the code while ignoring comments, character vectors, and string literals. Variable access includes reading, adding, removing, or modifying workspace variables.
In these coding contexts, MATLAB requires transparent variable access:
Function argument validation blocks. For more information, see Restrictions on Variable and Function Access
The body of a
parfor
loop orspmd
block. For more information, see Ensure Transparency in parfor-Loops or spmd Statements (Parallel Computing Toolbox).
In these contexts, nontransparent variable access results in run-time errors.
Writing Transparent Code
Transparent code refers to variable names explicitly. For example, in this code,
MATLAB can identify X
and ii
as
variables.
X = zeros(1,10); for ii = 1:10 X(ii) = randi(9,1); end
However, in the following call to the eval
function, MATLAB cannot recognize the variables in the statement that is passed to
eval
because the input is a character string.
X = zeros(1,10); for ii = 1:10 eval('X(ii) = randi(9,1);') end
Before executing this code, MATLAB sees a call to the eval
function with one argument, which
is the character vector 'X(ii) = randi(9,1);'
.
To be transparent, code must refer to variable names explicitly so that MATLAB can identify the variables by inspection or static analysis. Using the
eval
function with the character vector 'X(ii) =
randi(9,1);'
means that MATLAB must execute the code to identify X
and
ii
as variables.
Here is a partial list of functions and coding that you cannot use with transparent variable access:
Passing a variable to a function using the command form is not transparent because it is
equivalent to passing the argument as a character string. For example, these calls to the
clear
function are both
nontransparent.
clear X clear('X')
If code creates workspace variables, but MATLAB can identify these new variables only after executing the code, then this code does not have transparent variable access. For example, MATLAB cannot determine what variables are loaded from a MAT file, so this statement is nontransparent.
load foo.mat
However, code that explicitly assigns the loaded variable to a name is transparent
because MATLAB can recognize that the name on the left-hand side refers to a workspace
variable. For example, this statement loads the variable X
from the MAT
file into the workspace in a variable named X
.
X = load('foo.mat','X');
Access to variables must be transparent within the workspace. For example, code cannot
use the evalin
or assignin
functions in a workspace that requires transparency to create
variables in another workspace.