How can I average a 4-D array every nth element without using too much loops

조회 수: 2 (최근 30일)
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
Isma Di Carlo
Isma Di Carlo 2018년 6월 22일
The data is in seconds starting from 15th January 1947. I have a time table. Like I know a point corresponds to that point in time. I just need to make a monthly average and I estimated that 5 points of data = 1 month.
(The 4D array is because the 3rd object is the depth. I just only took the 10 first meters of my dataset)

댓글을 달려면 로그인하십시오.

채택된 답변

OCDER
OCDER 2018년 6월 21일
data = rand(476, 238, 1, 2699);
N = floor(2699/5);
data_zeros = zeros(476, 238, 1, N); %Preallocate this for speed
k = 1;
for i = 5:5:2699
data_zeros(:, :, 1, k) = mean(data(:, :, 1, i-4:i), 4); %Mean along 4th dimension
k = k+1;
end

추가 답변 (1개)

Walter Roberson
Walter Roberson 2018년 6월 21일
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 ?

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by