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

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

本文介绍了在Sympy中获取矩阵乘法的逐元素方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个矩阵,首先是稀疏的整数系数.

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}

一种方法是在sympy中指定一个矩阵,每个元素都是一个单独的符号:

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)

是否可以使用上面的MatrixSymbol进行处理,然后获得结果的元素方程式?

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

推荐答案

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

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

这篇关于在Sympy中获取矩阵乘法的逐元素方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:16