Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix multiplication, solve Ax = b solve for x

So I was given a homework assignment that 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 an 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 am having trouble finding a good resource to do such a thing.

Ex.

A = |1 0 0|
    |1 4 1|
    |0 0 1|

x = Unknown 3x1 matrix

b = |0 |
    |24| 
    |0 |

Solve for x

like image 754
Scalahansolo Avatar asked Mar 04 '14 04:03

Scalahansolo


People also ask

What is AXB in matrix?

Note that Ax is defined only if the number of columns of A equals the number of entries in x. The equation Ax = b is called a matrix equation. Theorem 3.


1 Answers

In a general case, 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 banded (which cubic splines it often is), then there's http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_banded.html

To comment on some of the comments to the question: better not use inv for solving linear systems. numpy.lstsq is a bit different, it's more useful for fitting.

As this is homework, you're really better off at least reading up on ways of solving tridiagonal linear systems.

like image 92
ev-br Avatar answered Oct 13 '22 22:10

ev-br