Can anyone help me with the a tentative guide on how to average across the two dimensions of a 3d array, and loop it across 86 timesteps?
6 views (last 30 days)
Show older comments
Its a climate data of type 720x360x86. Thank you.
0 Comments
Accepted Answer
Chad Greene
on 11 Oct 2021
Edited: Chad Greene
on 11 Oct 2021
If you have a temperature data cube T whose dimensions correspond to lat x lon x time, the simplest way to get an 86x1 array of mean temperature time series is
Tm = squeeze(mean(mean(T,'omitnan'),'omitnan'));
then you can make a line plot of mean temperature as a function of time, like this:
plot(t,Tm)
However, I should point out that all of the grid cells in a geographic grid have areas that depend on latitude, so it's not appropriate to give equal weight to a polar and equatorial grid cells (they're very different sizes!). In the Climate Data Toolbox for Matlab, see Example 3 of wmean for what I'm talking about.
It would be much better to get the area of each grid cell in your global grid using cdtarea like this:
A = cdtarea(Lat,Lon);
Then calculate the weighted mean like this:
Tm = NaN(86,1); % (preallocate for efficiency)
% Loop through each time step:
for k = 1:86
Tm(k) = wmean(T(:,:,k),A,'all');
end
% Get a mask of the grid cells that always have valid data:
mask = all(isfinite(T),3);
% Calculate weighted mean temperature time series in the finite grid cells:
Tm = local(T,mask,'weight',A);
More Answers (1)
Dave B
on 10 Oct 2021
Let's do this with a smaller array, as the specific numbers don't seem particularly important. I'll do 5x4x3 so we can see the values easily. It's actually very easy because MATLAB works naturally with matrices of any shape, you can do this all with the mean function, no loops required:
X = rand(5,4,3)
a=mean(X,1) % mean across rows (same as mean(X))
b=mean(X,2) % mean across columns
You might find the shape of these outputs to be annoying, the squeeze function is good for fixing that up:
squeeze(a)
squeeze(b)
12 Comments
See Also
Categories
Find more on Climate Science and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!