Search code examples
excelmatlabxlsread

using xlsread in matlab to loop through all .xls files in a folder


I'm writing a script that needs to loop through all the .xls files in a folder and pull data from specific cells. I think xlsread is capable of this, but I keep getting an error that reads:

Matlab:xlsread:filenotfound

Here is the basic structure of the code:

files = dir('C:\folder\folder\folder\*.xls');
channelinfo = 'C:\differentfolder\chanloc.type';
cnt = '.cnt';
condition = 'varriable';


for i = 1:length(files(:,1))
    try

        CNTCrash1WindowStart = xlsread(files(i).name, 'Summary', 'C8');
        CNTCrashWindowEnd = xlsread(files(i).name, 'Summary', 'D8');
        subjectNum = xlsread(files(i).name, 'User Info', 'A2');

        eeglab;
        %eeglab things happen here

    catch ME
        disp(ME)
    end
end            

Solution

  • The problem here is that your files are not located in your pwd (Present Working Directory). The call to dir gives you file names, but not including the full path name. Hence xlsread is looking for your .xls files in a location where they are not. Fix this by setting a temporary name where you include the full path and feed that to xlsread:

    folder = 'C:\folder\folder\folder\'; %'//
    files = dir([folder, '*.xls']);
    channelinfo = 'C:\differentfolder\chanloc.type';
    cnt = '.cnt';
    condition = 'variable';
    
    for ii = 1:length(files(:,1))
        try
            tempname = fullfile(folder, files(ii).name); %// Thanks to excaza
            CNTCrash1WindowStart = xlsread(tmpname, 'Summary', 'C8');
            CNTCrashWindowEnd = xlsread(tmpname, 'Summary', 'D8');
            subjectNum = xlsread(tmpname, 'User Info', 'A2');
    
            eeglab;
            %eeglab things happen here
    
        catch ME
            disp(ME)
        end
    end