Main Content

Share Data Between Workspaces


This topic shows how to share variables between workspaces or allow them to persist between function executions.

In most cases, variables created within a function are local variables known only within that function. Local variables are not available at the command line or to any other function. However, there are several ways to share data between functions or workspaces.

Best Practice: Passing Arguments

The most secure way to extend the scope of a function variable is to use function input and output arguments, which allow you to pass values of variables.

For example, create two functions, update1 and update2, that share and modify an input value. update2 can be a local function in the file update1.m, or can be a function in its own file, update2.m.

function y1 = update1(x1)
   y1 = 1 + update2(x1);

function y2 = update2(x2)
   y2 = 2 * x2;

Call the update1 function from the command line and assign to variable Y in the base workspace:

X = [1,2,3];
Y = update1(X)
Y =
     3     5     7

Nested Functions

A nested function has access to the workspaces of all functions in which it is nested. So, for example, a nested function can use a variable (in this case, x) that is defined in its parent function:

function primaryFx
   x = 1;

   function nestedFx
      x = x + 1;

When parent functions do not use a given variable, the variable remains local to the nested function. For example, in this version of primaryFx, the two nested functions have their own versions of x that cannot interact with each other.

function primaryFx

   function nestedFx1
      x = 1;

   function nestedFx2
      x = 2;

For more information, see Nested Functions.

Persistent Variables

When you declare a variable within a function as persistent, the variable retains its value from one function call to the next. Other local variables retain their value only during the current execution of a function. Persistent variables are equivalent to static variables in other programming languages.

Declare variables using the persistent keyword before you use them. MATLAB® initializes persistent variables to an empty matrix, [].

For example, define a function in a file named findSum.m that initializes a sum to 0, and then adds to the value on each iteration.

function findSum(inputvalue)
persistent SUM_X

if isempty(SUM_X)
   SUM_X = 0;
SUM_X = SUM_X + inputvalue;

When you call the function, the value of SUM_X persists between subsequent executions.

These operations clear the persistent variables for a function:

  • clear all

  • clear functionname

  • Editing the function file

To prevent clearing persistent variables, lock the function file using mlock.

Global Variables

Global variables are variables that you can access from functions or from the command line. They have their own workspace, which is separate from the base and function workspaces.

However, global variables carry notable risks. For example:

  • Any function can access and update a global variable. Other functions that use the variable might return unexpected results.

  • If you unintentionally give a “new” global variable the same name as an existing global variable, one function can overwrite the values expected by another. This error is difficult to diagnose.

Use global variables sparingly, if at all.

If you use global variables, declare them using the global keyword before you access them within any particular location (function or command line). For example, create a function in a file called falling.m:

function h = falling(t)
   global GRAVITY
   h = 1/2*GRAVITY*t.^2;

Then, enter these commands at the prompt:

global GRAVITY
y = falling((0:.1:5)');

The two global statements make the value assigned to GRAVITY at the command prompt available inside the function. However, as a more robust alternative, redefine the function to accept the value as an input:

function h = falling(t,gravity)
   h = 1/2*gravity*t.^2;

Then, enter these commands at the prompt:

y = falling((0:.1:5)',GRAVITY);

Evaluating in Another Workspace

The evalin and assignin functions allow you to evaluate commands or variable names from character vectors and specify whether to use the current or base workspace.

Like global variables, these functions carry risks of overwriting existing data. Use them sparingly.

evalin and assignin are sometimes useful for callback functions in graphical user interfaces to evaluate against the base workspace. For example, create a list box of variable names from the base workspace:

function listBox
lb = uicontrol('Style','listbox','Position',[10 10 100 100],...

function update_listBox(src,~)
vars = evalin('base','who');
src.String = vars;

For other programming applications, consider argument passing and the techniques described in Alternatives to the eval Function.

Related Topics