Clear Filters
Clear Filters

How to compile the average values of a variable in .mat files

1 view (last 30 days)
I have 81 .mat files that correspond to the years 1930 to 2010 and each contain a variable named 'zdaily'. In each zdaily, there are is a matrix that is 240x121x366or365 depending on if that year was a leap year or not. I'm trying to create a 'for loop' that will not only compile the .mat files into one large matrix but also take the average over the time dimension so that instead of 81x365or366, it will just be 81. Thanks
  2 Comments
Giridharan Kumaravelu
Giridharan Kumaravelu on 23 Jul 2018
Edited: Giridharan Kumaravelu on 23 Jul 2018
average = zeros(81,1);
for i = 1:81
data = matfile("filenameOfyear1930+i.mat");
average(i) = mean(data.zdaily,3);
end
Is this what you wanted?

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 23 Jul 2018
Edited: Adam Danz on 23 Jul 2018
Let's say your mat file is called 'myMatFile.mat' and the variable of interest is 'zdaily'.
% Pull data from file
filename = 'C:\Users\me\Documents\MATLAB\myMatFile.mat';
data = matfile(filename);
zdaily = data.zdaily;
% Average over the 2nd dim
m = mean(zdaily ,2);
% Check size
size(m) %should be [1,81]
The same thing with less lines of code (faster & cleaner)
data = matfile('C:\Users\me\Documents\MATLAB\myMatFile.mat');
m = mean(matfile.zdaily,2);
  2 Comments
Paul Torres
Paul Torres on 24 Jul 2018
There are 81 different .mat files, this code would only work for one, right?
Adam Danz
Adam Danz on 24 Jul 2018
Edited: Adam Danz on 24 Jul 2018
Yes, you'd need to implement a loop as Giridharan demonstrated in the comments section above. For example, you could create a cell array of all your filenames and loop through each element of the cell array.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!