简体   繁体   中英

Creat symbol matrix using numpy, sympy in function?

My code:

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

Error message:

TypeError: can't convert expression to float

You probably don't want numpy matrix'es to store sympy 's symbols. Better use sympy.Matrix for this.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM