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

时间:2022-06-23 20:20:04

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

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

1 个解决方案

#1


0  

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

你可能不希望numpy matrix'es存储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]

#1


0  

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

你可能不希望numpy matrix'es存储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]