Matlab(TM): Reading/loading multiple files

I got this piece of Matlab(TM) code by searching through google cache. 

This is a question I get asked frequently; most recently by a friend who was visiting this week. He has several data files saved in a single directory, which he needs to read and process recursively. All the files are named myfile###.mat. Here is a run-down on how to do this in Matlab.

The main command you need to know for this purpose is eval. Eval parses the string constant and evaluates its result, as if this string was entered on Matlab command line. For example, the following two statements are equivalent:
>> a1 = 5;
>> eval(['a1 = 5;']);

Note that the string passed on to eval is exactly the same as that executed on the command line.

Lets play a little more with the string constant being passed on to it.
>> i = 1
>> ['a', num2str(i), ' = 5;']

This command returns the string: ‘a1 = 5;’
Hint: be careful about the spaces. This command converts the value of integer i into a string constant ('1') and concatenates it with the other strings.

Consequently, the following gives the same result as the first command:
>> eval([’a’, num2str(i), ‘ = 5;’])

Sequential File Reading

Equipped with this knowledge, we will use the eval command for sequentilly reading files
for i = 1:100
    eval(['load myfile', num2str(i)])
    % Other statements for processing data
end

An improved method for more complicated names

I use the above method for reading and parsing files when the counter i has a certain meaning, such as, say length of a reactor that I am studying. However, there is another method that I use when the names are not exactly as straightforward.

For example, I need to recursively read files “myfile###.mat”, where ### can be any alphanumeric string. Lets say that the alphanumeric string ### has a certain meaning. Among other things, each files contains temperatures, and I want to read the maximum value of the temperatures for all these files. For this purpose, I will use the dir command (which gives directory listing in Matlab). The code is as follows:

dirList = dir;
parsedTData = [];
for i = 3:length(dir)
    currFile = dirList(i).name;
    % Thanks Rick! (See comment 1)

    if( length(currFile) < 6 )
        cycle% Skip short file names
    end
    if ( currFile(1:6) ~= ‘myfile’)
        cycle % Skip files not starting with ‘myfile’
    end
    mnemonic = currFile(7:end-4); % Obtain part of the
    file name between ‘myfile’ and ‘.mat’

    load(currFile);
    maxT = max(temperature);
    temp{1} = mnemonic; temp{2} = maxT;
    parsedTData = [parsedTData; temp];
end

Thats All Folks! Hope this helps.

Update: Modified the code according to comment from Rick.

Discussion Area - Leave a Comment