Load workspace in background "thread" in MATLAB

Alec Jacobson

March 27, 2012

weblog/

Here's a proof of concept that you can run in your matlab IDE that loads a workspace from a file in a background, worker thread. I imagine this is useful if you want to keep your Matlab session open, but have a 3rd party program be able to talk to matlab, (not just be called from matlab (mex) or call matlab functions (matlab engine). First create some dummy workspaces.
X = 1;
save('workspace.mat','X');
X = 2;
save('workspace2.mat','X');
Now run this code to start the background "thread":
% load the global workspace from 'workspace.mat' every 1 second, print value of X
t = timer('TimerFcn','load(''workspace.mat'');disp(X)','Period',1,'ExecutionMode','fixedDelay');
start(t);
You should see that matlab is spitting out:
X =
     1
But in the meantime you could issue matlab calls like:
Y = 'banana'
Now pretend you're a third party program that wants to send a new value of X to the matlab session. Do this by copying our dummy workspace2.mat onto the workspace.mat that's being polled:
!cp workspace2.mat workspace.mat
Now we see that it has worked as matlab is spitting out:
X = 
    2
Finally stop the polling and clean up the timer:
stop(t);
delete(t);