Loading multiple .mat files containing the same variable name and changing the variable names simultaneously?
Mostrar comentarios más antiguos
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?
Respuestas (1)
Star Strider
el 24 de Jun. de 2015
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 comentarios
Ta Na
el 24 de Jun. de 2015
Star Strider
el 24 de Jun. de 2015
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.
Categorías
Más información sobre File Operations en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!