I'm trying to make a function with the arguments (a,tol=1e-8)
that returns a boolean value that tells the user whether or not the matrix is symmetric (symmetric matrix is equal to its transpose). So far I have:
def check_symmetric(a, tol=1e-8):
if np.transpose(a, axes=axes) == np.transpose(a, axes=axes):
return True
def sqr(s):
rows = len(s)
for row in sq:
if len(row) != rows:
return False
return True
if a != sqr(s):
raise ValueError
although I keep getting an axes isn't defined
message so I'm pretty sure that doesn't work at all...... the tests I'd like to pass are:
e = np.eye(4)
f = np.diag([1], k=3)
g = e[1:, :]
print(check_symmetric(e))
print(not check_symmetric(e + f))
print(check_symmetric(e + f * 1e-9))
print(not check_symmetric(e + f * 1e-9, 1e-10))
try:
check_symmetric(g)
print(False)
except ValueError:
print(True)
Any help is appreciated, thanks!
A Simple solution is to do following. 1) Create transpose of given matrix. 2) Check if transpose and given matrices are same or not.
How to check Whether a Matrix is Symmetric or Not? Step 1- Find the transpose of the matrix. Step 2- Check if the transpose of the matrix is equal to the original matrix. Step 3- If the transpose matrix and the original matrix are equal, then the matrix is symmetric.
You can simply compare it to its transpose using allclose
def check_symmetric(a, rtol=1e-05, atol=1e-08):
return numpy.allclose(a, a.T, rtol=rtol, atol=atol)
The following function also solves the problem:
def check_symmetric(a, tol=1e-8):
return np.all(np.abs(a-a.T) < tol)
If you're not worried about the tot
threshold
(a==a.T).all()
is the simplest solution. This works for N-dimensional (N>2) arrays as well.
This is an old post but I would recommend another method. Especially for sparse matrices, this can be hundreds of times faster.
def is_symmetric(A, tol=1e-8):
return scipy.sparse.linalg.norm(A-A.T, scipy.Inf) < tol;
Or similar but you get the idea. Using a norm is a much more optimized calculation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With