Matrix multiplication, solution Ax = b for x

Therefore, I was assigned homework, which requires solving the coefficients of cubic splines. Now I clearly understand how to do the math on paper, as well as with MatLab, I want to solve the problem with Python. Given the equation Ax = b, where I know the values โ€‹โ€‹of A and b, I want to be able to solve for x with Python, and I'm having trouble finding a good resource to do such a thing.

Ref.

A = |1 0 0| |1 4 1| |0 0 1| x = Unknown 3x1 matrix b = |0 | |24| |0 | 

Solve for x

+8
python numpy matrix-multiplication
source share
3 answers

In general, use solve :

 >>> import numpy as np >>> from scipy.linalg import solve >>> >>> A = np.random.random((3, 3)) >>> b = np.random.random(3) >>> >>> x = solve(A, b) >>> x array([ 0.98323512, 0.0205734 , 0.06424613]) >>> >>> np.dot(A, x) - b array([ 0., 0., 0.]) 

If your problem is grouped (which cubic splines it often happens), then http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_banded.html

Comment on some comments on the question: it is better not to use inv for solving linear systems. numpy.lstsq slightly different, it is more useful for installation.

Since this is homework, you really should at least read ways to solve tridiagonal linear systems.

+9
source share

Numpy is the core scientific computing package in Python. If you are a Windows user, download it here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy else follow these instructions: http://www.scipy.org/install.html .

 import numpy A = [[1,0,0],[1,4,1],[0,0,1]] b = [0,24,0] x = numpy.linalg.lstsq(A,b) 
+2
source share

In addition to the Zhenya code, you might also find the use of the np.dot function intuitive:

 import numpy as np A = [[1,0,0], [1,1,1], [6,7,0]] b = [0,24,0] # Now simply solve for x x = np.dot(np.linalg.inv(A), b) #np.linalg.inv(A) is simply the inverse of A, np.dot is the dot product print x Out[27]: array([ 0., 0., 24.]) 
0
source share

All Articles