python - 如何在python中制作矩阵矩阵?(值错误)
问题描述
所以我想制作一个 2x2 H 矩阵,其中包含两个矩阵,如下所示:
H 中的矩阵应该是一个 dim x dim 矩阵,其中 v 值在主对角线上,w 值在主对角线下方的对角线上。
这是这个程序:
def make_ham(v,w,dim):
V = (scipy.sparse.eye(dim,k=0)*v).todense()
W = (scipy.sparse.eye(dim,k=-1)*w).todense()
Γ = V+W
line = np.array([0,0,1,1])
column = np.array([0,1,0,1])
data = np.array([0,1,1,0])
Hb = scipy.sparse.csc_matrix((data,(line,column)), shape=(2,2), dtype=(np.float64))
H = kron(Hb, Γ)*[[1],[0]]+kron(Hb, Γ.T)*[[0],[1]]
return H
当我给出一个不是 2 的暗淡时,我得到这个错误:
ValueError: shapes (3,3) and (2,1) not aligned: 3 (dim 1) != 2 (dim 0)
我真的被困在这里,所以提前感谢您的任何建议!:)
解决方案
这是您可以使用 numpy 执行的操作:
import numpy as np
#Size of the inside matrices
N = 2
#Setting values of v and w for instance
v = 1
w = 2
#Making H a diagonal matrix
H = np.eye(N)
np.where(H==1, v, H) #Replacing 0 values by v
np.where(H==0, w, H) #Replacing 0 values by w
#Filling the upper triangle with random values (For instance)
T = np.random.random((N, N))
T *= 1-np.tri(*T.shape)
#Redefining H with the upper triangle
H = H + T
#Creating a null matrix of the shape as H
Z = np.zeros_like(H)
#Creating matrix of matrix
matrix_of_matrix = np.array([[Z,H],[H.T,Z]])
print(matrix_of_matrix)
推荐阅读
- android - 升级android应用,如何覆盖sqlite
- reactjs - 从canvasjs的react js中渲染多个图形
- node.js - 过滤角材料
- python-3.x - 为什么在 Flask 中放置路由时出现 SQL IntegrityError?
- flutter - 变换 FlutterRenderer 或 SurfaceTexture
- r - 根据单独的参考表过滤数据框
- jpa - 无法使用 JPA 上的请求结果类型错误为具有多个返回的查询创建 TypedQuery
- python - 有没有办法在修补套接字时避免修补 IPython 嵌入?
- asp.net - 团队:个人选项卡 => 成功的身份验证重定向回登录页面(由于未设置 cookie)
- python - 无法在 localhost(8888) 连接到 pigpio 无法创建回调线程。可能有太多的同时 pigpio 连接