How to solve sparse matrices in python: A *x = f

In many engineering problems, sparse matrices arise: Electrical engineering, Chemical engineering, Civil engineering (structural calculations), Finite element methods (FEM), etc.

Below is an example of a sparse matrix:

The question is: How to solve this array in Python?

Library to be used: Scipy and numpy.
Both scipy and numpy have linalg (linear algebra). scipy is more complete

Attempt to solve

import numpy as np
from scipy.sparse.linalg import spsolve
from scipy.sparse import csr_matrix

-----INPUT-----

F = 1000
n11 = F / 3
n12 = 2 * F / 3
xa = 0.2
alfa1 = 0.8
alfa2 = 0.9
alfa3 = 0.1

----- EXPRESSIONS -----

Data from the rows (row) and columns (col) of the matrix

row = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 10, 10, 11, 15])
col = np.array([0, 9, 2, 10, 2, 11, 0, 3, 0, 1, 4, 2, 5, 3, 6, 6, 9, 4, 7, 10, 5, 8, 11, 3, 9, 4, 10, 5, 15])

data = np.array(
[-1, 1, -1, 1, -1, 1, -(1 - xa), 1, xa, -1, 1, -xa, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, -1, alfa1, -1, alfa2, -1,
alfa3, -1])

Creating the sparse matrix

csr_matrix() = create sparse matrix in row (rows)

A = csr_matrix((data, (row, col)), shape=(29, 29)).toarray()

if you print A generates matrix with zeros - OK

print(A)

1 Question:
How to declare b?

Not is:
b = np.array([-n11, - n12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

=> it’s wrong. Do I only want rows and columns that have values?

2 - How to declare x = A-1 * b ?? THIS IS MY PROBLEM :frowning_face:

3 - The Scipy documentation doesn’t show you how to do this. Shows only simple and straightforward problems.

4 - I want to solve x and print:

m1 = x[0]
m2 = x[1]
m3 = x[3]

print(’ the value of m1 is = ‘. m1)
print(’ the value of m2 is = ‘. m2)
print(’ the value of m2 is = '. m2)

Anyone know how to solve this problem the way row, col, data was assembled?

What makes you say it’s wrong? Did you get an error? What exactly did you try and what exact error did you get?

Is there some simple example you’ve tried to extend? Where did you get stuck?

You need to declare fields with arrays.
Those fields are called “tuples”.

It is explained here in documentation below :

https://docs.python.org/3/tutorial/datastructures.html