使用Python實現(xiàn)生成對角矩陣和對角塊矩陣
矩陣可視化
為了展現(xiàn)不同矩陣之間的差別,在具體介紹scipy中的不同矩陣之前,先構造一個用于繪制矩陣的函數(shù)
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中的函數(shù)
在scipy.linalg中,通過tri(N, M=None, k=0, dtype=None)可生成N × M N\times MN×M對角矩陣,若M=None,則M MM默認為N NN。k表示矩陣中用1填充的次對角線個數(shù)。
print(tri(3,5,2,dtype=int)) ''' [[1 1 1 0 0] [1 1 1 1 0] [1 1 1 1 1]] '''
在numpy中也提供了多種對角矩陣生成函數(shù),包括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用于調節(jié)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可用于提取出矩陣的左下和右上的三角陣,其輸入?yún)?shù)除了待提取矩陣之外,另一個參數(shù)與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實現(xiàn)生成對角矩陣和對角塊矩陣的文章就介紹到這了,更多相關Python對角矩陣內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python實現(xiàn)Web服務器FastAPI的步驟詳解
FastAPI?是一個用于構建?API?的現(xiàn)代、快速(高性能)的?web?框架,使用?Python?3.6+?并基于標準的?Python類型提示,這篇文章主要介紹了Python實現(xiàn)Web服務器FastAPI的過程,需要的朋友可以參考下2022-06-06python3+pyqt5+itchat微信定時發(fā)送消息的方法
今天小編就為大家分享一篇python3+pyqt5+itchat微信定時發(fā)送消息的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02