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.

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. Using the eval function with the character vector 'X(ii) = randi(9,1);' means that MATLAB must execute the code before being able to identify X and ii.

Here is a partial list of functions and coding that you cannot use with transparent variable access.

  • eval, evalc, evalin, or assignin.

  • Scripts

  • MEX functions that access the workspace variables dynamically, for example by using mexGetVariable.

  • Introspective functions such as who and whos.

  • The save and load commands, except when the result from load is assigned explicitly.

  • Any dynamic name reference, such as using the clear command.

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 the MAT file, so this statement is nontransparent.

load foo.mat

However, code that assigns the loaded variable to a name explicitly 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 to create variables in another workspace from a workspace that requires transparency.

Related Topics