Code covered by the BSD License  

Highlights from
safesave

safesave

by

 

Safely save your data to a mat-file

safesave(filename,varargin)
function [] = safesave(filename,varargin)

% FUNCTION:
%   [] = safesave(filename,varargin)
%
% DESCRIPTION:
%   Saves specified input arguments to a mat-file 
%   and creates a backup of the original file if necessary
%
% INPUT ARGUMENTS:
%   filename = string containing desired filename (either with or without '.mat' extension)
%   varargin = comma-separated list of variables to save (NOT strings: the function uses the original variable names)
%
% OUTPUT ARGUMENTS:
%   -
%
% EXAMPLE CODE:
%
%   % Update variables a and b and store results in mat-file 'example.mat' with back-ups if necessary
%   for i = 1:3
%       a=i;
%       b=2*i;
%       safesave('example',a,b); 
%   end
%
% Author: D.J. van Gerwen
% Created: 10-Dec-2010

% Process input arguments
if nargin < 2
    error('safesave requires at least two input arguments: a file name and one or more variables to save to that file...')
end

% Make sure that extension is included in filename (*.mat)
if ~strcmp( filename(end-3:end), '.mat' )
    filename = [filename '.mat']; % If extension not present, add it.
end

% Assign caller's variable names
nonamecount = 0;
varstring = '';
for i = 1:length(varargin)
    if ~isempty(inputname(1+i))
        varname = inputname(1+i);
    else
        nonamecount = nonamecount + 1;
        varname = ['noname' num2str(nonamecount,'%03.0f')]
    end
    varstring = [varstring ',''' varname ''''];
    eval([varname ' = varargin{i};']);
end
    
% First, if necessary, create backup-copy of original mat-file
if exist(filename,'file')
    backupcount = 0; % Backup file counter [-]
    backupname = @(backupcount) [filename(1:end-4) '_backup_' num2str(backupcount,'%03.0f') '.mat']; % Define anonymous function for backup-name
    while exist(backupname(backupcount),'file')
        backupcount = backupcount + 1; % Increment counter [-]
    end
    copyfile(filename,backupname(backupcount)); % Copy original file to backup file
end

% Save data to new mat-file
savestring = ['save(''' filename '''' varstring ')']; % String with save() command
eval(savestring); % Evaluate string (i.e. save the data)

Contact us