Dennis Roth
Dennis Roth

Reputation: 85

Solving A*x=x with numpy

I am new to numpy and I want to solve the equation A * x = x, where A is a matrix and x is a vector.

Searching for the vector x, if it exists.

I found the np.linalg.solve()-function , but didn't got it to work as intended.

Upvotes: 0

Views: 1317

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114330

The issue here is not so much a problem with numpy as with your understanding of the linear algebra involved. The question you are asking can be rephrased as:

A @ x = x
A @ x = I @ x
(A - I) @ x = 0

This is a specific formulation of the the general eigenvector problem, with the stipulation that the eigenvalue is 1.

Numpy solves this problem with the function np.linalg.eig:

w, v = np.linalg.eig(A)

You need to check if any of the values are 1 (there could be more than one):

mask = np.isclose(w, 1)
if mask.any():
    for vec in v[:, mask].T:
        print(vec)
else:
    print('Nope!')

The elements of v are unit vectors. Keep in mind that any scalar multiple of such a vector is also a solution.

For issues with non-invertible matrices, you may want to use scipy.linalg.svd instead:

v, w, _ = svd(A)

The rest of the procedure will be the same.

Upvotes: 4

Related Questions