Linear Algebra by Code - Inverse Matrices

Basic Rules of Inverse Matrix



For n by n(n>2) matrix, the determinant will be talked about in the coming article. Here, just give an example of 3 by 3 matrix:


K is a 3 by 3 matrix, I is a identity matrix.

In linear algebra, a tridiagonal matrix is a band matrix that has nonzero elements only on the main diagonal, the first diagonal below this, and the first diagonal above the main diagonal. - Wikipedia

Tip: Diagonally dominant matrices are invertible. Each `|a_{ii}|` dominates its row, namely `|a_{ii}|>sum_(i!=j)|a_{ij}|`


C++

The matrix M is a Triangular Pascal matrix whose inverse matrix has "alternating diagonals", namely odd-numbered diagonals have minus signs.

#include <iostream>
#include <Eigen/Dense>

using namespace Eigen;
using namespace std;

int main()
{
    MatrixXf M(4,4);
    M << 1, 0, 0, 0,
         1, 1, 0, 0,
         1, 2, 1, 0,
         1, 3, 3, 1;

    cout << "Here is the matrix A:\n" << M << endl;
    cout << "The determinant of A is " << M.determinant() << endl;
    cout << "The inverse of A is:\n" << M.inverse() << endl;

    //Another way is to solve ax=b, i.e. M·inverse(M)=I
    const int size = 4;
    MatrixXd identity(size, size);
    identity = MatrixXd::Identity(size, size);
    MatrixXd x = M.colPivHouseholderQr().solve(identity);
    cout << x << endl;
} 

OUT(inverse matrix):

 1  0  0  0
-1  1  0  0
 1 -2  1 -0
-1  3 -3  1


Python

The same matrix as above is used:

import numpy as np
from scipy.linalg import pascal
from numpy.linalg import inv
from scipy.linalg import det
from scipy.linalg import solve

m = pascal(4, kind='lower')
mdet = det(m) # determinant of m
minv = inv(m) # inverse matrix of m

#Another way is to solve ax=b, i.e. m·inv(m)=I 
identity = np.eye(4)
x = solve(m,identity)


Tensorflow

The same matrix as above is used:

import tensorflow as tf
import numpy as np
from scipy.linalg import pascal

m = pascal(4, kind='lower')
minv = tf.matrix_inverse(m.astype(float)) # tf doesn't support int type
mdet = tf.matrix_determinant(m.astype(float))

diagonal = [1,1,1,1]
diagonal = np.array(diagonal).astype(float)
identity = tf.diag(diagonal)
minv_solve = tf.matrix_solve(m.astype(float), identity) # ax=b

with tf.Session() as sess:
    print(mdet.eval())
    print(minv.eval())
    print(minv_solve.eval())


The next article will talk about Factorization.

登录注册后参与评论