且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Sympy中获取矩阵乘法的逐元素方程

更新时间:2022-03-10 03:37:58

结果是,这个问题的答案很明显:

Turns out, this question has a very obvious answer:

MatrixSymbol 进行索引矩阵,即:

MatrixSymbols in sympy can be indexed like a matrix, i.e.:

X[i,j]

给出了基于元素的方程式.

gives the element-wise equations.

如果要对一个以上的元素进行子集化,则必须首先将MatrixSymbol转换为sympy.Matrix类:

If one wants to subset more than one element, the MatrixSymbol must first be converted to a sympy.Matrix class:

X = sympy.Matrix(X)
X        # lists all indices as `X[i, j]`
X[3:4,2] # arbitrary subsets are supported

请注意,这不允许对numpy数组/矩阵进行所有操作(例如使用布尔等效项进行索引),因此***创建带有sympy符号的numpy数组:

Note that this does not allow all operations of a numpy array/matrix (such as indexing with a boolean equivalent), so you might be better of creating a numpy array with sympy symbols:

ijstr = lambda i,j: sympy.Symbol(name+"_{"+str(int(i))+","+str(int(j))+"}")
matrix = np.matrix(np.fromfunction(np.vectorize(ijstr), shape))