在Matlab中平均向量的每n个元素 [英] Averaging every n elements of a vector in matlab

查看:82
本文介绍了在Matlab中平均向量的每n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Matlab中对向量的每3个值取平均值,然后将平均值分配给产生该平均值的元素.

I would like to average every 3 values of an vector in Matlab, and then assign the average to the elements that produced it.

示例:

x=[1:12];
y=%The averaging operation;

手术后

y=
[2 2 2 5 5 5 8 8 8 11 11 11]

因此产生的向量大小相同,并且每3个值的跳跃平均值将替换用于产生平均值的值(即1 2 3被这三个值的平均值2 2 2代替).有没有办法做到这一点而没有循环?

Therefore the produced vector is the same size, and the jumping average every 3 values replaces the values that were used to produce the average (i.e. 1 2 3 are replaced by the average of the three values, 2 2 2). Is there a way of doing this without a loop?

我希望这是有道理的.

谢谢.

推荐答案

我会这样:

重整向量,使其成为3×x矩阵:

Reshape the vector so that it is a 3×x matrix:

x=[1:12];
xx=reshape(x,3,[]);
% xx is now [1 4 7 10; 2 5 8 11; 3 6 9 12]

之后

yy = sum(xx,1)./size(xx,1)

现在

y = reshape(repmat(yy, size(xx,1),1),1,[])

精确地产生您想要的结果.

produces exactly your wanted result.

您的参数3表示值的数量,仅在一个位置使用,可以根据需要轻松修改.

Your parameter 3, denoting the number of values, is only used at one place and can easily be modified if needed.

这篇关于在Matlab中平均向量的每n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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