Averaging every n elements of a vector in matlab

后端 未结 2 1765
你的背包
你的背包 2020-12-19 17:58

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

Examples:

x=[1:12];
y=%T         


        
相关标签:
2条回答
  • 2020-12-19 18:16

    I would go this way:

    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]
    

    after that

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

    and now

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

    produces exactly your wanted result.

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

    0 讨论(0)
  • 2020-12-19 18:28

    You may find the mean of each trio using:

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

    To duplicate the mean and reshape to match the original vector size, use:

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

    0 讨论(0)
提交回复
热议问题