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

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

 更新時(shí)間:2024年01月18日 10:15:07   作者:微小冷  
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)生成對角矩陣和對角塊矩陣,文中的示例代碼講解詳細(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}")

對角矩陣

scipy中的函數(shù)

在scipy.linalg中,通過tri(N, M=None, k=0, dtype=None)可生成N × M N\times MN×M對角矩陣,若M=None,則M MM默認(rèn)為N NN。k表示矩陣中用1填充的次對角線個(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中也提供了多種對角矩陣生成函數(shù),包括diag, diagflat, tri, tril, triu等,

numpy.diagflat

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

>>> 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用于調(diào)節(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ù)除了待提取矩陣之外,另一個(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()

對角塊矩陣

對于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)生成對角矩陣和對角塊矩陣的文章就介紹到這了,更多相關(guān)Python對角矩陣內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

钟山县| 广丰县| 凤山市| 安丘市| 砚山县| 庄浪县| 探索| 武威市| 陵水| 翼城县| 黑水县| 久治县| 内丘县| 宜春市| 蓬莱市| 十堰市| 莱芜市| 富民县| 孙吴县| 华宁县| 德州市| 金山区| 伊宁县| 新绛县| 安达市| 涡阳县| 台前县| 汉寿县| 石门县| 沂源县| 饶阳县| 江安县| 正蓝旗| 甘谷县| 五台县| 清水河县| 尉氏县| 墨脱县| 宁乡县| 昌宁县| 平山县|