MATLAB: Autorename if saved file already exist

MATLABsavesaveas

is there an option in save (or any other function) which support automatic renaming if the filename already exists or do I need to check by myself? (like saving as file2.mat if file.mat already exist)

Best Answer

You have to check it by your own if a file is existing already.
[EDITED: Consider {File.txt, File3.txt}]
function SaveWithNumber(FileName, Data)
[fPath, fName, fExt] = fileparts(FileName);
if isempty(fExt) % No '.mat' in FileName
fExt = '.mat';
FileName = fullfile(fPath, [fName, fExt]);
end
if exist(FileName, 'file')
% Get number of files:
fDir = dir(fullfile(fPath, [fName, '*', fExt]);
fStr = lower(sprintf('%s*', fDir.name);
fNum = sscanf(fStr, [fName, '%d', fExt, '*']);
newNum = max(fNum) + 1;
FileName = fullfile(fPath, [fName, sprintf('%d', newNum), fExt]);
end
save(FileName, 'Data');
Limitations: "FileNameInf.txt" and "FileNameNaN.txt" will cause troubles...
Consider, that:
exist(FileName, 'file')
replies TRUE for directories also.
Related Question