MATLAB: Copy file to a new folder

copy

Under a folder, I have a lot of .mat. "19800101.mat", "19800102.mat", ……."19800201.mat", "19800202.mat", ……"19801201.mat"…. I want to copy "19800101.mat", "19800102.mat", and copy others which also belong to January to a new folder, and display this new folder directory. February to a another new folder, and so on. Thanks.

Best Answer

destdirs = {'January', 'February', 'March', ... 'December'};
ndests = length(destdirs);
for K = 1 : ndests
if ~exist(destdirs{K}, 'dir'); mkdir(destdirs{K}); end
end
dinfo = dir('*.mat');
filenames = {dinfo.name};
%remove filenames that are not a 4 digit year followed by a 2 digit month followed by a
%2 digit day followed by .mat. Years starting in 0, 1, or 2 are accepted with this check
namebad = cellfun(@isempty, regexp(filenames, '[012]\d\d\d[01]\d\d\d\.mat$') );
filenames(namebad) = [];
nfiles = length(filenames);
for K = 1 : nfiles
thisfile = filenames{K};
monthnum = sscanf(thisfile, '%*4d%2d', 1);
if monthnum > ndests
fprintf('File has invalid month number, skipping "%s"\n', thisfile);
else
destdir = destdirs{monthnum};
copyfile( thisfile, destdir );
end
end
Related Question