To efficiently distribute images from a single directory into multiple subfolders, you can use the ‘copyfile’ method inside a loop. The script below copies images from a source directory into multiple destination folders, with each folder containing a specified number of images. I have tried it on MATLAB R2024b:
sourceDir = 'C:\Users\ SampleImages';
destDir = 'C:\Users \Output';
imageFiles = dir(fullfile(sourceDir, '*.png'));
numFolders = ceil(length(imageFiles) / imagesPerFolder);
for folderIdx = 1:numFolders
folderName = fullfile(destDir, sprintf('Folder_%02d', folderIdx));
if ~exist(folderName, 'dir')
startIdx = (folderIdx - 1) * imagesPerFolder + 1;
endIdx = min(folderIdx * imagesPerFolder, length(imageFiles));
for imgIdx = startIdx:endIdx
sourceFile = fullfile(sourceDir, imageFiles(imgIdx).name);
destFile = fullfile(folderName, imageFiles(imgIdx).name);
copyfile(sourceFile, destFile);
disp('Images have been copied into folders successfully.');
Here is the step-by-step process:
- The code first calculates the number of folders to be created and then creates those folders.
- It then distributes the images among these folders. The variable ‘imagesPerFolder’ defines the number of images to be placed in each destination folder.
- The ‘copyfile’ method is used to copy the files from the source to the destination folder. Alternatively, you can use ‘movefile’ to move the files instead of copying them.
Please refer to the documentations for more details:
I hope this solves your problem. Thanks!