Pages

Monday 9 May 2016

Matlab script for checking and deleting folders

Just putting this simple but extremely useful matlab script for my future self and anyone trying to handle folders using matlab. This script checks all the sub directory within the starting directory and then deletes the one that do not satisfy a given criteria. In my case this was the number of image samples within a folder.

% script for deleting folders with less than a certain number of files
close all
clear all
clc

% count the number of png files
D = dir(' ');


numFoldersOrFiles = size(D, 1);

thresholdFiles = 30;

% skipping the first two which are just . and ..
for i = 3: numFoldersOrFiles
    
    if D(i).isdir
        
        Ds = dir([D(i).name '\*.png']);
        numFiles = size(Ds, 1) / 3;
        if numFiles < thresholdFiles
            
            rmdir(D(i).name, 's');
            
        end
    end
end


% all done :)