矩阵

使用 mat 方法将 2 维数组转化为矩阵:

In [1]:

  1. import numpy as np
  2. a = np.array([[1,2,4],
  3. [2,5,3],
  4. [7,8,9]])
  5. A = np.mat(a)
  6. A

Out[1]:

  1. matrix([[1, 2, 4],
  2. [2, 5, 3],
  3. [7, 8, 9]])

也可以使用 Matlab 的语法传入一个字符串来生成矩阵:

In [2]:

  1. A = np.mat('1,2,4;2,5,3;7,8,9')
  2. A

Out[2]:

  1. matrix([[1, 2, 4],
  2. [2, 5, 3],
  3. [7, 8, 9]])

利用分块创造新的矩阵:

In [3]:

  1. a = np.array([[ 1, 2],
  2. [ 3, 4]])
  3. b = np.array([[10,20],
  4. [30,40]])
  5.  
  6. np.bmat('a,b;b,a')

Out[3]:

  1. matrix([[ 1, 2, 10, 20],
  2. [ 3, 4, 30, 40],
  3. [10, 20, 1, 2],
  4. [30, 40, 3, 4]])

矩阵与向量的乘法:

In [4]:

  1. x = np.array([[1], [2], [3]])
  2. x

Out[4]:

  1. array([[1],
  2. [2],
  3. [3]])

In [5]:

  1. A * x

Out[5]:

  1. matrix([[17],
  2. [21],
  3. [50]])

A.I 表示 A 矩阵的逆矩阵:

In [6]:

  1. print A * A.I
  1. [[ 1.00000000e+00 0.00000000e+00 0.00000000e+00]
  2. [ 0.00000000e+00 1.00000000e+00 2.08166817e-17]
  3. [ 2.22044605e-16 -8.32667268e-17 1.00000000e+00]]

矩阵指数表示矩阵连乘:

In [7]:

  1. print A ** 4
  1. [[ 6497 9580 9836]
  2. [ 7138 10561 10818]
  3. [18434 27220 27945]]

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/03-numpy/03.12-matrix-object.ipynb