对角矩阵

scipy中的函数

scipy.linalg中,通过tri(N, M=None, k=0, dtype=None)可生成 N × M N\times M N×M对角矩阵,若M=None,则 M M M默认为 N N Nk表示矩阵中用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用于生成对角矩阵,diagdiagflat基础上,添加了提取对角元素的功能,例如

>>> 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用于调节01的分界线相对于对角线的位置,例如

>>> np.tri(3,5,1)
array([[1., 1., 0., 0., 0.],
       [1., 1., 1., 0., 0.],
       [1., 1., 1., 1., 0.]])
>>> np.tri(3,5,2)
array([[1., 1., 1., 0., 0.],
       [1., 1., 1., 1., 0.],
       [1., 1., 1., 1., 1.]])
>>> np.tri(3,5,3)
array([[1., 1., 1., 1., 0.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

tril, triu可用于提取出矩阵的左下和右上的三角阵,其输入参数除了待提取矩阵之外,另一个参数与tri中的k相同。

x = np.arange(12).reshape(4,3)
>>> np.tril(x,-1)
array([[ 0,  0,  0],
       [ 3,  0,  0],
       [ 6,  7,  0],
       [ 9, 10, 11]])
>>> np.triu(x,-1)
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 0,  7,  8],
       [ 0,  0, 11]])

对角块矩阵

对于scipy.linalg.block_diag(A,B,C)而言,会生成如下形式矩阵

A 0 0 0 B 0 0 0 C \begin{matrix} A&0&0\\0&B&0\\0&0&C\\ \end{matrix} A000B000C

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

其bd打印结果是一个矩阵

[ 1. 1. 0. 0. 0. 0. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.8 0.38 0.41 0. 0. 0. ⋅ 0. 0. 0.84 0.45 0.24 0. 0. 0. ⋅ 0. 0. 0.32 0.22 0.25 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 3. ] \begin{bmatrix} 1.&1.&0.&0.&0.&0.&0.&0. \\ 1.&1.&0.&0.&0.&0.&0.&0. \\ 0.&0.&0.8&0.38&0.41&0.&0.&0.·\\ 0.&0.&0.84&0.45&0.24&0.&0.&0.·\\ 0.&0.&0.32&0.22&0.25&0.&0.&0. \\ 0.&0.&0.&0.&0.&1.&0.&0. \\ 0.&0.&0.&0.&0.&0.&2.&0. \\ 0.&0.&0.&0.&0.&0.&0.&3. \end{bmatrix} 1.1.0.0.0.0.0.0.1.1.0.0.0.0.0.0.0.0.0.80.840.320.0.0.0.0.0.380.450.220.0.0.0.0.0.410.240.250.0.0.0.0.0.0.0.1.0.0.0.0.0.0.0.0.2.0.0.0.0.0.0.0.0.3.

其中

A = [ 1 1 1 1 ] B = [ 0.8 0.38 0.41 0.84 0.45 0.24 0.32 0.22 0.25 ] C = [ 1 0 0 0 2 0 0 0 3 ] A=\begin{bmatrix}1&1\\1&1\end{bmatrix}\quad B=\begin{bmatrix}0.8 &0.38&0.41\\0.84&0.45&0.24\\0.32&0.22&0.25\end{bmatrix}\quad C=\begin{bmatrix}1&0&0\\0&2&0\\0&0&3\end{bmatrix} A=[1111]B= 0.80.840.320.380.450.220.410.240.25 C= 100020003

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐