1

I'm optimizing my codes. Now I have an MxN matrix, and I want to generate a mean MxN matrix which is the mean of other rows

for example: if i have matrix A:

1 2 3

3 4 5

2 3 2

In the new matrix B, I want each one is the mean of other rows.

mean(row2,row3)

mean(row1,row3)

mean(row1,row2)

I've think of many ways, but can't avoid a loop

    for row=1:3
        temp = A;
        temp(row,:) = [];
        B(row,:) = mean(temp);
    end

any thoughts?

FF0605
  • 441
  • 7
  • 17

1 Answers1

2

Simple with bsxfun -

B = (bsxfun(@minus,sum(A,1),A))./(size(A,1)-1)

The trick is to subtract the current row from the sum all rows with bsxfun in a vectorized manner, thus giving us the sum of all rows except the current one. Finally, get the average values by dividing them by the number of rows minus 1.

Divakar
  • 218,885
  • 19
  • 262
  • 358
  • smart way! it may be okay to get rid of the "." before "/" too – FF0605 Nov 16 '15 at 06:51
  • @FF0605 Not at all! `./` means elementwise division, what is we need, not the matrix division of `/`. – Divakar Nov 16 '15 at 06:59
  • what I meant was (size(A,1)-1) is a single number, so it doesn't really matter if it's elementwise :P thanks for the smart solution! – FF0605 Nov 17 '15 at 06:35
  • Dear Divakar, I just posted another question to avoid loop in a matrix, could you please have a look? – FF0605 Nov 18 '15 at 07:54