Search code examples
matlabdirectorysequential

Retrieve data from different folders that are named sequentially


I have several folders each named sequentially i.e. Center Left P1, Center Left P2 etc. Within each folder I have 38 ".dat" files which contain data that I want for analysis. Is it possible to create a Matlab script which will open each folder and retrieve the ".dat" files? Sorry I am relatively new to matlab and previously I have been manually naming each file in Matlab in order to get the data I need. But this would take too long in this case. Regards, Jerry


Solution

  • You can use dir command and fullfile commands for this purpose.

    myData = cell(1,numFolders);
    for p=1:numFolders
        folderName = sprintf('Center Left P%d', p ); % current folder name
        %// working with relative paths. If abs paths are used, remove leading '.' 
        datFiles = dir( fullfile( '.',  folderName, '*.dat' ) ); %// should return a list of all dat files in specific folder
        myData{p} = cell( 1, numel(datFiles) );
        for di=1:numel(datFiles)
            myData{p}{di} = importdata( fullfile( '.', folderName, datFiles(di).name ) ); %// read data
        end
    end