Getting element-wise equations of matrix multiplication in sympy

梦想与她 提交于 2019-12-23 15:04:15

问题


I've got 2 matrices, first of which is sparse with integer coefficients.

import sympy
A = sympy.eye(2)
A.row_op(1, lambda v, j: v + 2*A[0, j])

The 2nd is symbolic, and I perform an operation between them:

M = MatrixSymbol('M', 2, 1)
X = A * M + A.col(1)

Now, what I'd like is to get the element-wise equations:

X_{0,0} = A_{0,0}
X_{0,1} = 2*A_{0,0} + A_{0,1}

One way to do this is specifying a matrix in sympy with each element being an individual symbol:

rows = []
for i in range(shape[0]):
    col = []
    for j in range(shape[1]):
        col.append(Symbol('%s_{%s,%d}' % (name,i,j)))
    rows.append(col)
M = sympy.Matrix(rows)

Is there a way to do it with the MatrixSymbol above, and then get the resulting element-wise equations?


回答1:


Turns out, this question has a very obvious answer:

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

X[i,j]

gives the element-wise equations.

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

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))


来源:https://stackoverflow.com/questions/28531244/getting-element-wise-equations-of-matrix-multiplication-in-sympy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!