Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average for all elements in a row except the element itself - MATLAB

For a given matrix A, how can i create a matrix B of the same size where every column is the mean (or any other function) of all the other columns?

example: a function on

A = [
     1     1     1
     2     3     4
     4     5     6]

should result in

B = [ 
      1   1  1 
      3.5 3 2.5
      5.5 5 4.5]
like image 416
fn.mat Avatar asked Mar 02 '26 18:03

fn.mat


1 Answers

Perfect setup for bsxfun -

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

Explanation: Breaking it down to two steps

Given

>> A
A =
     1     1     1
     2     3     4
     4     5     6

Step #1: For each element in A, calculate the sum of all elements except the element itself -

>> bsxfun(@minus,sum(A,2),A)
ans =
     2     2     2
     7     6     5
    11    10     9

Step #2: Divide each element result by the number of elements responsible for the summations, which would be the number of columns minus 1, i.e. (size(A,2)-1) -

>> bsxfun(@minus,sum(A,2),A)./(size(A,2)-1)
ans =
    1.0000    1.0000    1.0000
    3.5000    3.0000    2.5000
    5.5000    5.0000    4.5000
like image 118
Divakar Avatar answered Mar 05 '26 10:03

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!