In my program, I need the following matrix multiplication:
A = U * B * U^T
where B
is an M * M
symmetric matrix, and
You observed that So U, a 10*5 matrix, is indeed orthonormal except numerical rounding causes not exactly identity.
The same reasoning applies to A
- it is symmetric except for numerical rounding:
In [176]: A=np.dot(U,np.dot(B,U.T))
In [177]: np.allclose(A,A.T)
Out[177]: True
In [178]: A-A.T
Out[178]:
array([[ 0.00000000e+00, -2.22044605e-16, 1.38777878e-16,
5.55111512e-17, -2.49800181e-16, 0.00000000e+00,
0.00000000e+00, -1.11022302e-16, -1.11022302e-16,
0.00000000e+00],
...
[ 0.00000000e+00, 0.00000000e+00, 1.11022302e-16,
2.77555756e-17, -1.11022302e-16, 4.44089210e-16,
-2.22044605e-16, -2.22044605e-16, 0.00000000e+00,
0.00000000e+00]])
I use np.allclose
when comparing float arrays.
I also prefer ndarray
and np.dot
over np.matrix
because element by element multiplication is just as common as matrix multiplication.
If the rest of the code depends on A
being symmtric, then your trick may be a good choice. It's not computationally expensive.
For some reason einsum
avoids the numerical issues:
In [189]: A1=np.einsum('ij,jk,lk',U,B,U)
In [190]: A1-A1.T
Out[190]:
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
In [193]: np.allclose(A,A1)
Out[193]: True