How can I average a 4-D array every nth element without using too much loops
Show older comments
Hi,
So I am currently working on a (476,238,1,2699) array using MatLab 2017a corresponding to (longitude, latitude, 1, time). I basically want to make a monthly average of the data (so every 5th point). The problem is I tried using a loop but it takes so much time. Here is the code I am using :
data_zeros = [];
for i = 1:2699
for j = 1:238
for k = 1:476
if (mod(i, 5) == 0)
data_zeros(k,j,1,i) = mean(data(k,j,1,i-4:i));
i
j
k
end
end
end
end
I need your insight, please help :) !
3 Comments
dpb
on 21 Jun 2018
If you have data by time for lat,long, why store in a 4D array--why not use a time table or such to make the time-based operations simpler?
What form is the time data in?
Isma Di Carlo
on 22 Jun 2018
Walter Roberson
on 22 Jun 2018
"I have a time table."
Use retime()
Accepted Answer
More Answers (1)
Walter Roberson
on 21 Jun 2018
mean( reshape(data, size(data,1), size(data,2), 5, size(data,4)/5 ), 3 )
I take advantage here of the fact that the third dimension is length 1 to pull in groups of 5 into the third dimension and mean() along that dimension.
However, you have the difficulty that your data is not an exact multiple of 5 long in that dimension. How do you want to take the mean of the entries 2696:2699 ?
1 Comment
Isma Di Carlo
on 22 Jun 2018
Categories
Find more on Cell Arrays 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!