英文:
Separate symbolic matrix in a sum of matrices sympy
问题
我有一个符号矩阵,其中元素是不同的函数。这是一个示例:
import sympy as sp
a, b, c, d = sp.symbols('a, b, c, d')
M = sp.Matrix([[a, b], [c, d]])
我想将M
重写为未知矩阵写法的和,就像这样:
M = a * sp.Matrix([[1, 0], [0, 0]]) + b * sp.Matrix([[0, 1], [0, 0]]) + c * sp.Matrix([[0, 0], [1, 0]]) + d * sp.Matrix([[0, 0], [0, 1]])
或者作为不同函数的列表:
[a * sp.Matrix([[1, 0], [0, 0]]), b * sp.Matrix([[0, 1], [0, 0]]), c * sp.Matrix([[0, 0], [1, 0]]), d * sp.Matrix([[0, 0], [0, 1]])]
我的矩阵类似于这样:
英文:
I have a symbolic matrix where the elements are different functions. this is an example:
import sympy as sp
a,b,c,d = sp.symsbols('a, b, c, d')
M = sp.Matrix([[a, b], [c, d]])
I would like to rewrite the M
as sum of matrices without knowing how the matrix are written, like this:
M = a*sp.Matrix([1,0],[0,0]) + b*sp.Matrix([0,1],[0,0]) +c*sp.Matrix([0,0],[1,0])+ d*sp.Matrix([,0],[0,1])
or a list of the different functions:
[a*sp.Matrix([1,0],[0,0]), b*sp.Matrix([0,1],[0,0]) ,c*sp.Matrix([0,0],[1,0]), d*sp.Matrix([,0],[0,1])]
My matrix are some thing like this:
答案1
得分: 4
以下是翻译好的部分:
假设:
- 您的矩阵中的所有元素都是乘法(因此是
Mul
类型)。 i
是虚数单位。
您可以这样做:
M = Matrix([[2 * a * I, 4 * b], [3 * c, a]])
matrices = []
for s in M.free_symbols:
term = MatMul(s, M.applyfunc(lambda t: t.coeff(s)), evaluate=False)
matrices.append(term)
print(term)
# 输出:
b*Matrix([[0, 4], [0, 0]])
a*Matrix([[2*I, 0], [ 0, 1]])
c*Matrix([[0, 0], [3, 0]])
首先,我们循环遍历矩阵中包含的自由符号。您还可以手动插入符号列表... 使用M.applyfunc
,我们对矩阵的所有元素应用某个函数。根据前述的假设,我们正在检索矩阵的每个元素的特定符号的系数。请注意MatMul
内部的evaluate=False
:如果将其更改为True,则Sympy将评估乘法,导致一个带有符号的单个矩阵。
最终,您可以将这些项相加,例如:
MatAdd(*matrices, evaluate=False)
英文:
Assuming that:
- all the element of your matrices are multiplications (hence, of type
Mul
). i
is the imaginary number.
You can do something like this:
M = Matrix([[2 * a * I, 4 * b], [3 * c, a]])
matrices = []
for s in M.free_symbols:
term = MatMul(s, M.applyfunc(lambda t: t.coeff(s)), evaluate=False)
matrices.append(term)
print(term)
# out:
b*Matrix([[0, 4], [0, 0]])
a*Matrix([[2*I, 0], [ 0, 1]])
c*Matrix([[0, 0], [3, 0]])
First, we loop over the free symbols contained in the matrix. You could also manually insert a list of symbols... With M.applyfunc
we apply some function to all elements of the matrix. With the aforementioned assumptions, we are retrieving the coefficients of a particular symbol for each element of the matrix. Note the evaluate=False
inside MatMul
: if you change it to True, then Sympy evaluates the multiplication, resulting in a single matrix with the symbol inside it.
Eventually, you can add the terms together, for example:
MatAdd(*matrices, evaluate=False)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论