Jack Dawkins -4 years ago 315

Python Question

I want to solve the following linear system for

`x`

`Ax = b`

Where A is sparse and b is just regular column matrix. However when I plug into the usual

`np.linalg.solve(A,b)`

`np.linalg.solve(A.todense(),b)`

How can I use this linear solve still preserving the

`sparseness`

`A`

`A`

`150 x 150`

I hope my question makes sense. How should I go about achieving this?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

`np.linalg.solve`

only works for array-like objects. For example it would work on a `np.ndarray`

or `np.matrix`

(Example from the numpy documentation):

```
import numpy as np
a = np.array([[3,1], [1,2]])
b = np.array([9,8])
x = np.linalg.solve(a, b)
```

or

```
import numpy as np
a = np.matrix([[3,1], [1,2]])
b = np.array([9,8])
x = np.linalg.solve(a, b)
```

or on `A.todense()`

where `A=scipy.sparse.csr_matrix(np.matrix([[3,1], [1,2]]))`

as this returns a `np.matrix`

object.

To work with a sparse matrix, you have to use `scipy.sparse.linalg.spsolve`

(as already pointed out by rakesh)

```
import numpy as np
import scipy.sparse
import scipy.sparse.linalg
a = scipy.sparse.csr_matrix(np.matrix([[3,1], [1,2]]))
b = np.array([9,8])
x = scipy.sparse.linalg.spsolve(a, b)
```

Note that `x`

is still a `np.ndarray`

and not a sparse matrix. A sparse matrix will only be returned if you solve Ax=b, with b being a matrix and not a vector.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**

Latest added