更快的复制文件Matlab

时间:2018-01-16 17:15:24

标签: matlab file copy vectorization cell-array

我的文件夹origin_training包含FMfolder1folder2...等子文件夹。我可以将.png格式的图像文件列表放入名为FM的单元格中。

FM_dir = fullfile(origin_training, 'FM');
FM = struct2cell(dir(fullfile(FM_dir, '*.png')))';

我的目标是将我的文件夹中的名称与cd中的图片相匹配,并使用FM中的图片制作一个新文件夹cd。两条路径中的图像名称相同。我可以这样做:

% mother_folder = '...' my current directory
filenames = FM(:,1);
destination = fullfile(mother_folder, 'FM', FM(:,1));
cellfun(@copyfile,filenames, destination);

这真的很慢。即使是少量图像也需要几分钟(~30)。

我当前的目录有~10000张图片(与FMfolder2folder3,...对应的图片。我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

另一种方法是创建一个shell命令并执行它。假设FM包含每个文件的完整路径或当前目录的相对路径,则:

FM_dir = fullfile(origin_training, 'FM');
destination = fullfile(mother_folder, 'FM');
curdir = cd(FM_dir);
FM = dir('*.png');
cmd = ['cp ', sprintf('%s ',FM.name), destination];
system(cmd);
cd(curdir);

如果您使用的是Windows,请将'cp'替换为'copy'

请注意,这里我们没有为每个要复制的文件创建一个shell命令(可能是copyfile所做的),而是一个shell命令,它一次复制所有文件。我们也没有为每个复制的文件指定名称,我们指定要复制的文件的名称以及将它们复制到的位置。

另请注意,为此,mother_folder必须是绝对路径。

答案 1 :(得分:0)

我以某种方式将我的代码放入一个函数中,现在它以预期的速度运行。我怀疑cd与低速有关,所以我只将完整目录作为字符向量传递。 同样的方法适用于我的目的或稍作修改,只需从A复制到B。与现在一样,它可以将A中的文件与B上的文件匹配并复制到B/folder_name

function [out] = my_copyfiles(origin_dir, folder_name, dest_dir, extension)

new_dir = fullfile(origin_dir, folder_name);

% Get a cell with filenames in the origin_dir/folder_name
% Mind transposing to have them in the rows
NEW = struct2cell(dir(fullfile(new_dir, extension)))';

dest_folder = fullfile(dest_dir, folder_name);

% disp(dest_folder)

if ~exist(dest_folder, 'dir')
mkdir(dest_folder)
end

%% CAUTION, This is the step
% Use names from NEW to generate fullnames in dest_dir that would match
filenames = fullfile(dest_dir, NEW(:,1));
destination = fullfile(dest_folder, NEW(:,1));

% if you wanted from origin, instead run
% filenames = fullfile(new_dir, NEW(:,1));

% make the copies
cellfun(@copyfile,filenames, destination);

%Save the call

out.originDir = new_dir;
out.copyFrom = dest_dir;
out.to = dest_folder;
out.filenames = filenames;
out.destination = destination;

end