简体   繁体   English

沿第3维度平均每4个条目

[英]Averaging every 4 entries along the 3rd dimension

How can I average every 4 data points along the 3rd dimension of a matrix? 如何平均矩阵的第3维上的每4个数据点?

My matrix is 245x85x1460 (lonxlatxhour). 我的矩阵是245x85x1460(lonxlatxhour)。 Since the 3rd dimension is 6 hourly data and I want daily data, I want to average every 4 data points (ie 1:4, 5:8, etc) and end up with a matrix of size 245x85x365. 由于第3维是6小时数据,我想要每日数据,我想平均每4个数据点(即1:4,5:8等),最终得到一个大小为245x85x365的矩阵。

Using reshape : 使用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. 需要squeeze功能将结果推回到三维阵列。 A(:,:,1) from above should be equivalent to mean(R(:,:,1:4),3) , and so on. A(:,:,1)应该等于mean(R(:,:,1:4),3) ,依此类推。

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. 假设您的数据存储在变量old_data中并且您需要new_data中的结果,则可以使用此示例代码。

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

It's best to use arrayfun for this kind of stuff. 最好将arrayfun用于这种东西。 Lets assume your original data is in matrix . 让我们假设您的原始数据是matrix

Create a 3-dimensional index vector for arrayfun to use: arrayfun创建一个三维索引向量以使用:

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. 使用arrayfun ,遗憾的是我们必须将UniformOutput指定为false ,这会导致单元格数组的结果。

resultcell=arrayfun(@(x) mean(matrix(:,:,4*x-3:4*x), 3), index3d,'UniformOutput',false);

Convert cell array to 3-dimensional matrix: 将单元格数组转换为三维矩阵:

result=cell2mat(resultcell);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM