在功能中使用numpy,sympy创建符号矩阵?

时间:2017-03-22 12:32:15

标签: python arrays numpy matrix sympy

我的代码:

def crearMatrix(name,shape=(2,2)):
    X = np.empty(shape)
    for i in range(shape[0]): #X.shape[1]
        for j in range(shape[1]):
            X[i][j] = Symbol("a"+'_{'+str(i*10+j+11)+'}')
    return X

错误讯息:

  

TypeError:无法将表达式转换为float

1 个答案:

答案 0 :(得分:0)

您可能不希望numpy矩阵存储sympy个符号。最好使用sympy.Matrix

import sympy

def crearMatrix(name,shape=(2,2)):
    X = []
    for i in range(shape[0]):
        row = []
        for j in range(shape[1]):
            row.append(sympy.Symbol("a"+'_{'+str(i*10+j+11)+'}'))
        X.append(row)
    return sympy.Matrix(X)

A = crearMatrix("a")
print(sympy.latex(A**2))

# \left[\begin{matrix}a_{11}^{2} + a_{12} a_{21} & a_{11} a_{12} + a_{12} a_{22}\\a_{11} a_{21} + a_{21} a_{22} & a_{12} a_{21} + a_{22}^{2}\end{matrix}\right]