Numpy linalg and solving a linear system of equations

We show here how to read a square matrix A from a file A.txt and a vector b from a file b.txt and print the solution x to the equation Ax = b.

#! /usr/bin/python3
# Define a vector and a matrix and compute the matrix-vector product

import numpy as np
from numpy import linalg as LA

# Read the matrix 
A = np.loadtxt("A.txt")

# Read the rhs vector
b = np.loadtxt("b.txt")

# Solve the linear system Ax = b
x = LA.solve(A,b)

# Print the solution

Here are the new features of the code:

from numpy import linalg as LA

The numpy package contains a linalg subpackage. It is automatically loaded with numpy, and it can be accessed with np.linalg. But with this command we can access it with LA instead and save typing.

x = LA.solve(A,b)

The linear algebra subpackage has functions starting with np.linalg. Here we access them with LA. The solve member of the subpackage that we use here takes a matrix and a vector and solves the linear system.

Try running the code to see the result.