1
votes

Let $xx = (I - u uT / (uT u)) x$, where I is the identity matrix, x is a vector, u is a vector, uT is the transposed u, and xx is the resulting vector.

I want to implement this equation in python, so I tried the following but I am not sure if my code corresponds to what the equation is expressing:

# given u and x, example:
u = np.array([ 0.7231519  -0.36004635 -0.82970352  1.1832742 ])
x = np.array([ 1.10667023 -1.13105657 -0.77213626  1.14220917])
uuT = np.array([u]) * np.array([u]).T
uTu = np.dot(u, u)
xx = (I - uuT / uTu).dot(x)

Is my code above correct ?

1

1 Answers

1
votes

It looks correct. However, you may want to do this in a more conventional fashion, i.e. using only matrix calculations. Commonly, "u-like" vectors are column, which by experience is confirmed by how u is subject to transposition. Let's create u and x as such

>>> import numpy as np
>>> u = np.array([ 0.7231519,  -0.36004635, -0.82970352, 1.1832742 ])[:,np.newaxis]
>>> x = np.array([ 1.10667023, -1.13105657, -0.77213626, 1.14220917])[:,np.newaxis]
>>> x.shape
(4, 1) # four rows and one column

Then one has to compute the cartesian product (which actually can be seen as a first approximation of the covariance matrix of u)

>>> uuT = np.dot(u, u.T)
>>> uuT
array([[ 0.52294867, -0.2603682 , -0.60000168,  0.85568699],
       [-0.2603682 ,  0.12963337,  0.29873172, -0.42603356],
       [-0.60000168,  0.29873172,  0.68840793, -0.98176677],
       [ 0.85568699, -0.42603356, -0.98176677,  1.40013783]])

and the (scalar) sum of squares

>>> uTu = np.dot(u.T, u)
>>> uTu
array([[ 2.74112781]])

finally

>>> I = np.eye(4)
>>> np.dot(I - uuT / uTu, x)
array([[ 0.26253613],
       [-0.71077502],
       [ 0.19637539],
       [-0.23902499]])