Skip to content
Advertisement

Centering matrix

I want to write a function for centering an input data matrix by multiplying it with the centering matrix. The function shall subtract the row-wise mean from the input.

My code:

JavaScript

But I get a wrong result matrix, it is not centered.

Thanks!

Advertisement

Answer

The centering matrix is

JavaScript

Here is a list of issues in your original formulation:

  1. np.ones(n).T is the same as np.ones(n). The transpose of a 1D array is a no-op in numpy. If you want to turn a row vector into a column vector, add the dimension explicitly:

    JavaScript

    OR

    JavaScript
  2. The normal definition is to subtract the column-wise mean, not the row-wise, so you will have to transpose and right-multiply the input to get row-wise operation:

    JavaScript
  3. Your function creates a new array for the output but does not currently return anything. You can either return the result, or perform the assignment in-place:

    JavaScript

    OR

    JavaScript

    OR

    JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement