Loading multiple .mat files containing the same variable name and changing the variable names simultaneously?

1.7k views Asked by At

So I have a directory that has many .mat files:

apples.mat, oranges.mat, bananas.mat, grapes.mat, apricots.mat, pears.mat, pineapple.mat

All of these .mat files has a variable name "calories" assigned a value. How do I load all of these .mat files simultaneously in MATLAB and change the variables for each one from calories to calories_(fruit name) so that I can have all the variable values in the workspace to play with?

For example, I want to load apples.mat and change its variable name from calories to calories_apple, then load oranges.mat and change is variable name from calories_orange, etc. without doing it all manually.

I know it's something along the lines of creating a string with the different fruit names, and the indexing along the string to load a file and change its variable from variable to variable_%s with the %s indicating the fruit content generated along the loop. It's a big mess for me, however, I don't think I'm structuring it right. Would anyone care to help me out?

2

There are 2 answers

11
rayryeng On BEST ANSWER

I would load each .mat file in sequence and put each of the corresponding calories as a separate field being all combined into a single struct for you to access. Given the directory of where these .mat files appear, do something like this:

%// Declare empty structure
s = struct()
folder = '...'; %// Place directory here

%// Get all MAT files in directory
f = dir(fullfile(folder, '*.mat'));

%// For each MAT file...
for idx = 1 : numel(f)

    %// Get absolute path to MAT file - i.e. folder/file.mat
    name = fullfile(folder, f(idx).name);

    %// Load this MAT file into the workspace and get the calories variable
    load(name, 'calories');

    %// Get the name of the fruit, are all of the characters except the last 4 (i.e. .mat)
    fruit_name = f(idx).name(1:end-4);

    %// Place corresponding calories of the fruit in the structure
    s.(['calories_' fruit_name]) = calories;
end

You can then access each of the calories like so using dot notation:

c = s.calories_apple;
d = s.calories_orange;

...
...

... and so on.

2
Pablo Rivas On

I am assuming that you do not mean to include the parenthesis in calories_(fruit name). I am also assuming there are no other .mat files in your current directory. This should do the trick:

theFiles = dir('*.mat');
for k = 1:length(theFiles)
    load(theFiles(k).name, 'calories');
    eval(['calories_' theFiles(k).name(1:length(theFiles(k).name)-4) ' =  calories;'])
    clear calories
end

Let me know if this helps or not.

EDIT As, rayryeng points out. The use of eval is, apparently, a bad practice. So, if you are willing to change the way you are thinking about the problem, I suggest you use a structure. In which case, rayryeng's response would be an acceptable answer, even though it does not directly answers your original question.