Load and average lots of .mat files

4 views (last 30 days)
Michael
Michael on 17 Jun 2011
I have been struggling with this since yesterday and appreciate some direction. I am new to matlab.
I have lots of .mat files which contain power spectra of a signal (1x1351 matrix) each from a different participant in the study. I need to load all these files into matlab and plot their average.
But the prblem is that even thouhg the .mat files have different names, the variable within the .mat is the same. So each time I load one in work space it overwrites the previous one.
Is there a clever way, perhaps a loop, that can do this and the averaging at the same time? Thanks Mike

Answers (3)

Arturo Moncada-Torres
Arturo Moncada-Torres on 17 Jun 2011
You can try using an intermediate variable to store the information you load from each file. On a quick thought, you must do something like this:
files = dir('*.mat'); % Get all of the files properties with a .mat extension
% Load the first file to know the length of the signal.
% If you already know it, you may skip this,
% assign accumulativeVector the known size (1351 in your case)
% and run the loop beginning in 1 (and not in 2).
load(files(1).name);
accumulatedVector = x;
% Sweep the rest of the files.
for i=2:length(files)
load(files(i).name); % Load the files. Notice how "eval" is not needed.
accumulatedVector = accumulatedVector + x; % x is the name of the variable.
end
accumulatedVector = accumulatedVector ./ length(files); % Average.
EDIT
I would like to add that in the first line, files is a structure containing the information (properties) of all the files in your current directory with a .mat extension.
When you refer to files(i).name (for example), you are extracting the property name (the file's name) of the file i of the structure files. That is the beauty of this =) . Try it and let me know if it works!

Gerd
Gerd on 17 Jun 2011
Hi Michael,
load the first file. Give the variable a different name, e.g. _index, load the next file. Again copy the variable to a new one _index2 and so on. Then you have all your data with the file index in your workspace
Gerd

Michael
Michael on 17 Jun 2011
Thanks guys.
Arturo, I am not very familiar with matlab conventions. I suppose that .name should be replaced with the name of the mat file in order to load it?
  1 Comment
Arturo Moncada-Torres
Arturo Moncada-Torres on 17 Jun 2011
See the edit please ;-) . Let me know if it works for you!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!