I want to calculate the mean of two rows in matlab

前端 未结 3 1689
别跟我提以往
别跟我提以往 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:41

    I think what you are looking for is:

    x = rand( 1028, 18 );
    meanx = ( x(1:2:end,:) + x(2:2:end,:)) / 2;
    

    After running this, meanx will be a [514 x 18] matrix.

    The first row of meanx is the average of rows 1 and 2 in x.

    The second row of meanx is the average of rows 3 and 4 in x.

    The third row of meanx is the average of rows 5 and 6 in x.

    EDIT:

    If you also want to exclude some of the rows from the averaging procedure based on the value of the first row, then you can add the following:

    dx = diff(x(:,1));
    
    goodrows = (dx(1:2:end) == 0);  %find row-pairs for which the first elements match
    badrows = ~goodrows;
    
    goodmeans = meanx(goodrows,:)  %average rows with matching first element
    badmeans = meanx(badrows,:)    %average rows with non-matching first element
    
    0 讨论(0)
  • 2021-01-29 05:46

    I think you want to calculate the column-wise mean of every pair of rows. Reshape the array to be 2 x 18*1028/2, calculate the mean (which operates column-wise), and reshape the result to be 1028/2 x 18:

    >> x = rand(1028, 18);
    >> result = reshape(x, 2, 1028/2*18);
    >> result = mean(result);
    >> result = reshape(result, 1028/2, 18);
    

    A quick test to demonstrate the speed of vectorized solution compared to a for-loop over pairs of rows:

    >> x = rand(1028, 18);
    >> tic; result1 = zeros(1028/2, 18); for ii = 1:1028/2; result1(ii,:) = mean(x((2*ii-1):(2*ii),:)); end; toc;
    Elapsed time is 0.022432 seconds.
    >> tic; result2 = reshape(x, 2, 1028/2*18); result2 = mean(result2); result2 = reshape(result2, 1028/2, 18); toc;
    Elapsed time is 0.000388 seconds.
    
    0 讨论(0)
  • 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..

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