Hello I have the following code which transposes one matrix and compares it to the original matrix in order to check if the matrix is symetrical.
def sym(x):
mat = x
transpose = 0;
(m,n) = x.shape
if(m != n):
print("Matrix must be square")
return
else:
transpose = ([[x[j][i] for j in range(len(x))] for i in range(len(x[0]))])
print(transpose)
print(x)
if(transpose == mat):
print("Symetrical")
else:
print("Not symetrical")
return
A = np.random.rand(5,5)
SymMatrix = (A A.T)/2
sym(SymMatrix)
I recieve the following data from the prints:
[[0.17439677739055337, 0.4578837676040824, 0.35842887026076997, 0.8610456087667133, 0.2967753611380975], [0.4578837676040824, 0.6694101430064164, 0.6718596412137644, 0.5107862111816033, 0.6429698779871544], [0.35842887026076997, 0.6718596412137644, 0.5387701626024015, 0.708555677626843, 0.5756758392540096], [0.8610456087667133, 0.5107862111816033, 0.708555677626843, 0.37095928395815847, 0.7062962356554356], [0.2967753611380975, 0.6429698779871544, 0.5756758392540096, 0.7062962356554356, 0.3807024190850993]]
[[0.17439678 0.45788377 0.35842887 0.86104561 0.29677536]
[0.45788377 0.66941014 0.67185964 0.51078621 0.64296988]
[0.35842887 0.67185964 0.53877016 0.70855568 0.57567584]
[0.86104561 0.51078621 0.70855568 0.37095928 0.70629624]
[0.29677536 0.64296988 0.57567584 0.70629624 0.38070242]]
along with this error:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The first issue i see is that the transposes matrix has extra decimals in each value which i dont understand and I am not sure if this is the cause of the error. Any help on this would be appreciated. Thanks!
CodePudding user response:
What you are doing is trying to compare two ndarrays, which results in something like this:
transpose == mat
array([[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True]])
The 'if' statement does not know which boolean he should pick. Should it be True
if any of the values are True
, or only if all values are True
?
To indicate that all values should be True
, add: .all()
to your statement:
if((transpose == mat).all())
This results in a single boolean (in this case: True
).