MATLAB: How to implement auto-save for Diary in MATLAB

autosaveMATLABtimerobj

I would like to save all the commands I enter in a given session of MATLAB. I
can place a Diary in startup.m and this works most of the time, but if MATLAB happens to crash, my diary does not save. It would be nice to have this file saved automatically periodically somehow.

Best Answer

You can use the TIMER function to generate a timer object and start this in your startup.m file. The callback that executes this will save the most current state of your diary into a file.
To name your diary file and update it every 5 seconds, the code in startup.m would be:
diaryname = ['Diary_' strrep(strrep(...
datestr(now),' ','_'),':','-') '.txt'];
diary(diaryname)
t = timer('timerfcn',@updatediary,...
'period',5,...
'ExecutionMode','fixedRate');
start(t)
The function updatediary needs to be on the MATLAB path and would contain the code:
function updatediary(obj, event, string_arg)
eval('base','diary off');
eval('base','diary on');