简体   繁体   English

在没有符号的情况下替换 Sympy 矩阵中的变量

[英]Substitute a variable in a Sympy matrix without having the symbol

Some function in my code returns a sympy.Matrix, but not the symbols that were used to create the matrix.我的代码中的某些函数返回 sympy.Matrix,但不是用于创建矩阵的符号。 I now want to substitute some of its value using its subs() method, but I do not have the symbols.我现在想用它的subs()方法替换它的一些值,但我没有符号。 Is there a way other than creating symbols with the same label again and using those?除了再次创建具有相同标签的符号并使用它们之外,还有其他方法吗?

Some piece of code to recreate the behavior would be the following:一些重新创建行为的代码如下:

import sympy as sp
x = sp.Symbol('x', real=True)
m = sp.Matrix([[0, x], [0, 0]])
x = 'something_else'
print(m.subs(x, 10))

If you are allowed to modify the code of your function, you could returned the symbols in the order of your liking:如果您被允许修改函数的代码,您可以按您喜欢的顺序返回符号:

def func():
    x, y, z = symbols("x, y, z")
    return x, y, z, Matrix([[x, y], [z, 0]])

Otherwise you could extract the symbols from the free_symbol attribute of a Matrix :否则,您可以从Matrixfree_symbol属性中提取符号:

from sympy import *
x, y, z = symbols("x, y, z")
M = Matrix([[x, y], [z, 0]])
list(M.free_symbols)
# out: [x, z, y]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM