Averaging all n elements of a vector in a matrix

I would like to average every 3 vector values ​​in Matlab, and then assign the average value to the elements that created it.

Examples:

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

After operation

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

Therefore, the resulting vector has the same size, and the average value of the jump every 3 values ​​replaces the values ​​that were used to obtain the average value (i.e. 1 2 3 are replaced by the average value of the three values 2 2 2 ). Is there a way to do this without a loop?

Hope this makes sense.

Thanks.

+4
source share
2 answers

I would go as follows:

Change 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] 

after that

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

and now

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

produces exactly your desired result.

Your parameter 3 , indicating the number of values, is used in only one place and can be easily changed if necessary.

+9
source

You can find the average value for each trio using:

x = 1:12;
m = mean(reshape(x, 3, []));

To duplicate the average value and change it to fit the original size of the vector, use:

y = m(ones(3,1), :) % duplicates row vector 3 times
y = y(:)'; % vector representation of array using linear indices

+3
source

Source: https://habr.com/ru/post/1441307/


All Articles