I want to calculate the mean of two rows in matlab

前端 未结 3 1681
别跟我提以往
别跟我提以往 2021-01-29 05:40

I have a 1028 by 18 matrix in matlab.I want to calculate the mean of 1st and 2nd row by column values,3rd and 4th and so on in Matlab and get a new matrix with the mean values.<

3条回答
  •  时光说笑
    2021-01-29 05:58

    Building on excellent answers by b3 and cjh. This one is the fastest

    m=1028;
    n=18;
    D=rand(m, n);
    
    % compute mean for two neighboring rows
    D=reshape(D, 2, m/2*n);
    D=(D(1,:)+D(2,:))/2;
    D=reshape(D, m/2, n);
    

    Measured in a for loop for 2000 iterations

    b3         Elapsed time is 0.264215 seconds.
    cjh        Elapsed time is 0.134812 seconds.
    my version Elapsed time is 0.087994 seconds.
    

    It is clear why. b3 uses function mean, which is not so good for performance if we just want to compute average of two numbers. On the other hand, clever reshapes make sure that we do not have to jump all over the memory during reading of the data, as is the case in the version of cjh. Hence, combining the best of the two solutions gives best results..

提交回复
热议问题