Thursday, April 16, 2009

MATLAB gem

On March 5, Daniel (I do not know anything else about the person) offered a MATLAB gem as a comment to Loren Shure's MATLAB blog Loren on the Art of MATLAB. In his comment he offered a way to save the state of the editor (i.e. all scripts open in the editor) in a .mat file which can be loaded at a later time and reset the editor with the exact same scripts. Though he suggests caution since it is 'undocumented functionality' I have found that it works well. It is very cool and useful!

Daniel's comment can be found here:


A few words about Loren's blog: It is one of the two The Mathworks blogs that I follow regularly. She is obviously an expert and she offers unique MATLAB insights (my kind of person). Almost every one of her blog entries gives me an opportunity to consider, think, and learn. 

So I used that and wrote my own function:

function setEditorState( filename, option )
%
%
% This is a neat trick that I picked up from Loren's blog offered by a guy
% named Daniel:
%
% http://blogs.mathworks.com/loren/2009/03/03/whats-in-your-startupm/#comment-30128
%
% The function same the state of the editor (all tabs open) to a file which
% can be reloaded and set the editor to the exact same state. Very cool!
%
% Inputs:
%     filename: String in single quotes without extention.
%     option: Strings 'save' or 'load'
%
% Example:
%     >> setEditorState( 'prova', 'save' )
%
% Note:
%     MAT files with the list of open files are always save in:
%
% <'C:\Documents and Settings\User\My Documents\MATLAB\Editor State Files\'>
%
%

% Error check number of input arguments
if (nargin <>
   error('myApp:argChk', 'Wrong number of input arguments')
end

% I want to save all save 'states' in a specific folder.
dirPath = 'C:\Documents and Settings\User\My Documents\MATLAB\Editor State Files\';

% Save editor state
if strcmpi(option, 'save') == 1
   
   editorServices = com.mathworks.mlservices.MLEditorServices;
   
   editorState = editorServices.builtinGetOpenDocumentNames();
   
   save ( [dirPath filename '.mat'], 'editorState', '-mat' );
   
% Load editor state
elseif strcmpi(option, 'load') == 1
   
   editorServices = com.mathworks.mlservices.MLEditorServices;
   
   load( [[dirPath filename '.mat']] )
   
   for id = 1:length( editorState )
      
      editorServices.openDocument( editorState(id) )
      
   end
   
end


2 comments:

  1. thank you! Indeed very helpful, saves lots of troubles...

    ReplyDelete
  2. You are welcome. You must work on multiple projects that have little in common :-)

    gk.

    ReplyDelete