使用Matlab的两个连续序列中数字的平均值 [英] Average of numbers in two consequetive sequences using Matlab

查看:161
本文介绍了使用Matlab的两个连续序列中数字的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,它是13867 X 2个元素,并存储在名为"data"的变量中.因此,我想在Matlab中执行以下操作:

I have an array that is 13867 X 2 elements and stored in variable called "data". So, I want to do the following in Matlab:

  • 平均值(第1行->第21行);即取前21个元素的平均值
  • 平均值(第22行->第43行);即取下22个元素的平均值
  • 平均值(第44行->第64行);即取下21个元素的平均值
  • 平均值(第65行->第86行);即取下22个元素的平均值
  • 重复该过程,直到矩阵末尾,以便我们从13847行到13876行取最后21个元素的平均值.我希望在第1列和第2列中取平均值.在Excel中执行此操作,但这是一项繁琐的任务(必须先为行创建索引).我想最终我们将获得645个平均值.

推荐答案

这样做的关键是插入NaN行,以使较短的块(21行)与较长的块(22行)具有相同的大小.使用

The key to doing that is inserting NaN rows to make the shorter blocks (21 rows) the same size as the longer blocks (22 rows). This is very easy, using the insertrows function from Matlab FileExchange:

n = 21;
m = 22;

dataPad = insertrows(data, nan(1,size(data,2)), n:(n+m):size(data,1));

在那之后,第22行将是[NaN, NaN],第66行将是[NaN, NaN],依此类推.现在,很容易计算平均值.只需对矩阵进行整形即可将所有应求平均值的值放在同一列上.最后,使用 nanmean 函数(仅忽略NaN的均值函数)以获取结果.

After that, row 22 will be [NaN, NaN], row 66 will be [NaN, NaN], and so on. Now it gets very easy to calculate the mean. Simply reshape this matrix so that all values which should be averaged are on the same column. Finally, use the nanmean function (mean function which simply ignores NaN) to get the result.

我不清楚结果应为645x2还是645x1,即是否对行进行平均.这是两种方式对应的reshape:

It is not 100% clear to me, whether the result should be 645x2 or 645x1, i.e. whether to average over the rows as well, or not. Here would be the corresponding reshape's for both ways:

1.也对行进行平均:

dataPadRearr = reshape(dataPad.',m*size(data,2),[]);
result = nanmean(dataPadRearr,1);

2..不理会这些行:

dataPadRearr = reshape(dataPad,m,[],size(data,2));
result = squeeze(nanmean(dataPadRearr,1));

请注意,在这里,您需要最终的 squeeze ,因为nanmean的结果将是尺寸1x645x2,这不是很实际. squeeze只是删除此单例尺寸.

Note that here, you'll need a final squeeze, as the result of nanmean would be of dimension 1x645x2, which is not very practical. squeeze just removes this singleton dimension.

这篇关于使用Matlab的两个连续序列中数字的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆