Reputation: 790
How can I average every 4 data points along the 3rd dimension of a matrix?
My matrix is 245x85x1460 (lonxlatxhour). Since the 3rd dimension is 6 hourly data and I want daily data, I want to average every 4 data points (i.e. 1:4, 5:8, etc) and end up with a matrix of size 245x85x365.
Upvotes: 3
Views: 392
Reputation: 17026
It's best to use arrayfun
for this kind of stuff. Lets assume your original data is in matrix
.
Create a 3-dimensional index vector for arrayfun
to use:
index3d=zeros(1,1,size(matrix,3)/4);
index3d(1,1,:)=(1:size(matrix,3)/4);
Use arrayfun
, unfortunately we must specify UniformOutput
to be false
which leads to a cell array as a result.
resultcell=arrayfun(@(x) mean(matrix(:,:,4*x-3:4*x), 3), index3d,'UniformOutput',false);
Convert cell array to 3-dimensional matrix:
result=cell2mat(resultcell);
Upvotes: 2
Reputation: 18484
Using reshape
:
R = rand(245,85,1460); % Some random data, same dimensions as your example
szR = size(R);
A = squeeze(mean(reshape(R,[szR(1:2) 4 szR(3)/4]),3)); % Mean across 3rd dimension
The squeeze
function is needed to push the result back down to a three-dimensional array. A(:,:,1)
from above should be equivalent to mean(R(:,:,1:4),3)
, and so on.
Upvotes: 4
Reputation: 4656
assuming that your data are stored in the variable old_data and you need a result in new_data, this sample code can be used.
new_data=zeros(245,85,365);
for k=0,364
new_data(:,:, k+1) = sum(old_data(:,:,4*k+1:4*k+4), 3)/4
end
Upvotes: 1