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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With