最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python實(shí)現(xiàn)生成對(duì)角矩陣和對(duì)角塊矩陣

 更新時(shí)間:2024年01月18日 10:15:07   作者:微小冷  
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)生成對(duì)角矩陣和對(duì)角塊矩陣,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

矩陣可視化

為了展現(xiàn)不同矩陣之間的差別,在具體介紹scipy中的不同矩陣之前,先構(gòu)造一個(gè)用于繪制矩陣的函數(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}")

對(duì)角矩陣

scipy中的函數(shù)

在scipy.linalg中,通過(guò)tri(N, M=None, k=0, dtype=None)可生成N × M N\times MN×M對(duì)角矩陣,若M=None,則M MM默認(rèn)為N NN。k表示矩陣中用1填充的次對(duì)角線個(gè)數(shù)。

print(tri(3,5,2,dtype=int))
'''
[[1 1 1 0 0]
 [1 1 1 1 0]
 [1 1 1 1 1]]
'''

在numpy中也提供了多種對(duì)角矩陣生成函數(shù),包括diag, diagflat, tri, tril, triu等,

numpy.diagflat

diagflat用于生成對(duì)角矩陣,diag在diagflat基礎(chǔ)上,添加了提取對(duì)角元素的功能,例如

>>> 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])) #提取對(duì)角元素
array([1., 1., 1.])

numpy.tri

tri(M,N,k)用于生成M行N列的三角陣,其元素為0或者1,k用于調(diào)節(jié)0和1的分界線相對(duì)于對(duì)角線的位置,例如

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ù)除了待提取矩陣之外,另一個(gè)參數(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()

對(duì)角塊矩陣

對(duì)于scipy.linalg.block_diag(A,B,C)而言,會(huì)生成如下形式矩陣

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()

繪圖結(jié)果如下

其中

到此這篇關(guān)于使用Python實(shí)現(xiàn)生成對(duì)角矩陣和對(duì)角塊矩陣的文章就介紹到這了,更多相關(guān)Python對(duì)角矩陣內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

乐都县| 深州市| 清水河县| 闵行区| 南阳市| 岳阳县| 什邡市| 聂拉木县| 康马县| 武胜县| 梁平县| 都安| 综艺| 大竹县| 南召县| 太仓市| 高碑店市| 中超| 普格县| 南昌县| 赞皇县| 麻栗坡县| 淮阳县| 高阳县| 巨鹿县| 阳春市| 四川省| 瓦房店市| 绿春县| 巴中市| 和顺县| 辰溪县| 阜平县| 南阳市| 资阳市| 怀仁县| 吉安市| 兴文县| 青海省| 宝应县| 秭归县|