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

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?

Answers (1)

Load them with an output:
apples = load('apples.mat');
will create a structure apples.calories when you load it. You can then easily keep track of each of them, with appropriate names.

2 Comments

You could possibly do that with an eval call, but that is not considered good programming practice.
Untested code:
file = 'apples';
eval(sprintf('%s = load(''%s.mat'')', file, file))
You would then have apples.calories in your workspace (you could put this in a loop to load the others as well), but using them might require repeated eval calls, considerably slowing your code.

Sign in to comment.

Categories

Asked:

on 24 Jun 2015

Commented:

on 24 Jun 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!