使用Python实现生成对角矩阵和对角块矩阵
作者:微小冷
这篇文章主要为大家详细介绍了如何使用Python实现生成对角矩阵和对角块矩阵,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
矩阵可视化
为了展现不同矩阵之间的差别,在具体介绍scipy中的不同矩阵之前,先构造一个用于绘制矩阵的函数
import matplotlib.pyplot as plt from itertools import product def drawMat(x, ax=None): M, N = x.shape if not ax: ax = plt.subplot() arrM, arrN = np.arange(M), np.arange(N) plt.yticks(arrM+0.5, arrM) plt.xticks(arrN+0.5, arrN) ax.pcolormesh(x) ax.invert_yaxis() for i,j in product(range(M),range(N)): if x[i,j]!=0: ax.text(j+0.2, i+0.55, f"{x[i,j]:.2}")
对角矩阵
scipy中的函数
在scipy.linalg中,通过tri(N, M=None, k=0, dtype=None)可生成N × M N\times MN×M对角矩阵,若M=None,则M MM默认为N NN。k表示矩阵中用1填充的次对角线个数。
print(tri(3,5,2,dtype=int)) ''' [[1 1 1 0 0] [1 1 1 1 0] [1 1 1 1 1]] '''
在numpy中也提供了多种对角矩阵生成函数,包括diag, diagflat, tri, tril, triu等,
numpy.diagflat
diagflat用于生成对角矩阵,diag在diagflat基础上,添加了提取对角元素的功能,例如
>>> np.diagflat([1,2,3]) array([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> np.diag([1,2,3]) array([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> np.diag(np.ones([3,3])) #提取对角元素 array([1., 1., 1.])
numpy.tri
tri(M,N,k)用于生成M行N列的三角阵,其元素为0或者1,k用于调节0和1的分界线相对于对角线的位置,例如
fig = plt.figure() mats = { 351:np.tri(3,5,1), 352:np.tri(3,5,2), 353:np.tri(3,5,3) } for i,key in enumerate(mats, 1): ax = fig.add_subplot(1,3,i) drawMat(mats[key], ax) plt.show()
tril, triu可用于提取出矩阵的左下和右上的三角阵,其输入参数除了待提取矩阵之外,另一个参数与tri中的k相同。
fig = plt.figure() x = np.arange(12).reshape(4,3) mats = [np.tril(x,-1),np.triu(x,-1)] for i,mat in enumerate(mats, 1): print(i, mat) ax = fig.add_subplot(1,2,i) drawMat(mat.astype(float), ax) plt.show()
对角块矩阵
对于scipy.linalg.block_diag(A,B,C)
而言,会生成如下形式矩阵
from scipy.linalg import * import numpy as np A = np.ones([2,2]) B = np.round(np.random.rand(3,3),2) C = np.diag([1,2,3]) bd = block_diag(A,B,C) drawMat(bd) plt.show()
绘图结果如下
其中
到此这篇关于使用Python实现生成对角矩阵和对角块矩阵的文章就介绍到这了,更多相关Python对角矩阵内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!