Matlab: Asynchronous Program Flow

Matlab scripts and functions are designed to run top-to-bottom, in a synchronous fashion. However, sometimes you need to run a piece of code "a little later", or in the background.

For such occasions, Yair Altman posted a trick on Undocumented Matlab. He uses a timer to call another function asynchronously. Simplifying his example, and using an anonymous function for the callback, this can be written as

timer_cb = @(obj, e, str) disp(str);

disp('first')
t = timer('StartDelay',0.1, 'TimerFcn',{timer_cb, 'second?'});
start(t)
disp('third?')

which outputs

first
third?
second?