首页 > 解决方案 > 如何在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)

我真的被困在这里,所以提前感谢您的任何建议!:)

标签: pythonnumpyscipysparse-matrix

解决方案


这是您可以使用 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)

推荐阅读