tchengaa
tchengaa

Reputation: 53

Linear algebra on python

i would like to use numpy.linalg.solve to solve a linear algebra equation, but i got an error message saying 'Last 2 dimensions of the array must be square'. Please shed some light thanks a lot !! here's my code:

import numpy as np
from numpy. linalg import solve

A = np.array([[3,-1,-1,0,0,0], [-1,4,-1,-1,0,0], [0,0,-1,-1,4,-1], [0,0,0,-1,-1,3]],float)

w = np.array([5,5,0,0],float)

v = solve(A,w)

print(v)

Upvotes: 5

Views: 14742

Answers (3)

Daniel B
Daniel B

Reputation: 322

So if you want A x = b and A is not square, you can simply do:

A_pseudoinverse = np.linalg.pinv(A)
x = A_pseudoinverse @ b

It's the same as @jandjob's answer, or at least close enough.

Upvotes: -1

jandob
jandob

Reputation: 649

As igavriil already wrote numpy.linalg.solve can only be used to find (the exact) solution for a well-determined system (i.e sqare coefficient matrix). If your system is under- or over-determined, there is usually no exact solution.

If you want to find an approximate solution, you can use numpy.linalg.lstsq. It uses a method called "least-squares-fitting" to find a solution that minimizes the overall error.

Upvotes: 6

igavriil
igavriil

Reputation: 1021

What this error basically says is that the linear system cannot be solved explicitly. This is because you have 6 variables and only 4 equations. In other words the coefficient matrix must be a square matrix. The error is raised when:

max(a.shape[-2:]) != min(a.shape[-2:]):

Upvotes: 3

Related Questions