MATLAB: How to reopen MATLAB scripts/function when the editor was accidentally closed

accidentclickclosefilesfunctionalityMATLABpreviousre-openreopenshutdownstate

How to reopen MATLAB scripts/function when the editor was accidentally closed?

Best Answer

Right now there are only workarounds for this functionality, because the development team is still investigating possible implementations for this feature.
Trying to find a solution, you could save all open files in a mat-file and reopen these after you close this. The issue is, that you have to pro-actively save the editor state.
If you did not do this, there is the following solution which uses a xml-file in the MATLAB preference directory.
In this xml-file the previous state of the MATLAB Editor was saved, so you can reopen all the closed files.
Please add the code to a Favorite in MATLAB, so you have a shortcut which can be easily used.
If you do not know how to add a Favorite, please read through: https://de.mathworks.com/help/matlab/matlab_env/create-matlab-favorites-to-rerun-commands.html
Here is the code which can be pasted into a Favorite:
%parse XML file
xmlFiles = xmlread([prefdir filesep 'MATLABDesktop.xml.prev']);
%Retrieve the "clients"
FileNodes = xmlFiles.getElementsByTagName('Client');
%get the length of the FileNodes
nrFiles = FileNodes.getLength;
%initialize Files
Files = cell(nrFiles,1);
%initialize isFile
isFile = zeros(nrFiles,1);
%Iterate over all Elements and check if it is a file.
for iNode = 0:nrFiles-1 % Java indexing.
%Files
Files{iNode+1} = char(FileNodes.item(iNode).getAttribute('Title'));
%check if the "client" is a file:
isFile(iNode+1) = exist(Files{iNode+1},'file') == 2 && ~(strcmp(Files{iNode+1},'Workspace'));
end
%remove the other files:
MyFiles = Files(find(isFile));
%open the files in the editor:
edit(MyFiles{:});