字符串乘以矩阵

时间:2018-09-17 21:27:22

标签: arrays string python-3.x numpy matrix

我试图将矩阵乘以我定义如下的常数:

E1 = "E1"
E2 = "E2"
J = "J"

但是,当我尝试将它们乘以下面定义的矩阵时,最终会出现错误:

# Defining the sigma functions and Identity matrices:
sigx = np.array([[0,1],[1,0]])
sigy = np.array([[0,-1j],[1j,0]])
sigz = np.array([[1,0],[0,-1]])
I1 = np.array([[1,0],[0,1]])
I2 = I1

enter image description here

# Trying to structure a Hamiltonian
H1 = np.kron(((E1)*(sigz)),I2)
H2 = np.kron((E2*(I1)),(sigz))
H3 = J*((np.kron((sigx),(sigx)))+(np.kron((sigy),(sigy))))
print(H1)
print(H2)
print(H3)
# Overall Hamiltonian Matrix 
Hs = H1 + H2 + H3
print(Hs)

enter image description here

如果我没有如上所示预先定义E1,E2或J,则该脚本有效,但是它只能工作,因为python自动为它们分配1,2,3的值。如何获得E1,E2和J出现在矩阵运算输出中?

2 个答案:

答案 0 :(得分:2)

第一次在这里发布。

我希望我不会说出显而易见的内容,但是看起来您正在将整数矩阵与字符串相乘。我认为您必须将常量定义为整数(或可能为doubles或floats) 。您正在使用Kronecker乘积进行矩阵乘法,但是将整数乘以字符串会导致dtype(U11)错误。

https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html

在这里您可以看到“ U11”错误表示一个低端11位字符Unicode字符串。

答案 1 :(得分:1)

为了让您入门,请先将您的代码翻译为sympy:

import sympy as sp

I1 = I2 = sp.eye(2)

# Pauli matrices
# (there is sympy.physics.paulialgebra but I do not know how to use it)
sigx = sp.Matrix([[0, 1], [1, 0]])
sigz = sp.diag(1, -1)
sigy = sigx * sigz * sp.I

# symbolic constants
E1, E2, J = sp.symbols('E1 E2 J')

kp = sp.kronecker_product

H1 = kp(E1 * sigz, I2)
H2 = kp(E2 * I1, sigz)
H3 = J * (kp(sigx, sigx) + kp(sigy, sigy))

Hs = H1 + H2 + H3

# now we can for example compute eigen decomposition
evals, mults, evecs = zip(*Hs.eigenvects())