Given a matrix arr
and a vector vec
, if vec
is eigenvector of arr
, then:
np.dot(arr, vec) == lambda_ * vec
therefore, going through all the values of np.dot(arr, vec) / vec
(eventually ignoring the null vector as potential eigenvector, and suppressing errors for potential division by zero), would reveal the eigenvalue:
import numpy as np
def find_eigenvalue(arr, vec):
result = None
if not np.all(np.isclose(vec, 0.0)):
with np.errstate(divide='ignore', invalid='ignore'):
for x, y in zip(np.dot(arr, vec), vec):
if np.isclose(y, 0.0) and np.isclose(x, 0.0):
continue
if result is None:
result = x / y
elif not np.isclose(result, x / y):
result = None
break
return result
which works as expected:
print(find_eigenvalue(arr, np.array([0, 0, 0])))
# None
print(find_eigenvalue(arr, np.array([1, 0, 0])))
# None
print(find_eigenvalue(arr, np.array([0, 1, 0])))
# None
print(find_eigenvalue(arr, np.array([0, 0, 1])))
# None
print(find_eigenvalue(arr, np.array([0, -1, 2])))
# 5
print(find_eigenvalue(arr, np.array([-5, 2, 1])))
# -0.0
print(find_eigenvalue(arr, np.array([1, 2, 1])))
# 6.0
Finally, note that np.linalg.svd()
will also compute all these:
u, s, vh = np.linalg.svd(arr)
and s
will contain the eigenvalues, and u
and vh
will contain the eigenvectors (more precisely the left-singular eigenvectors in u
and the hermitian of the right-singular eigenvectors in vh
).