SymPy - 替换矩阵中的符号条目 [英] SymPy - substitute sybolic entries in a matrix

查看:41
本文介绍了SymPy - 替换矩阵中的符号条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 函数,它生成一个带有符号条目的 sympy.Matrix.它的工作效率如下:

I have a python function which generates a sympy.Matrix with symbolic entries. It works effectively like:

import sympy as sp
M = sp.Matrix([[1,0,2],[0,1,2],[1,2,0]])

def make_symbolic_matrix(M):
    M_sym = sp.zeros(3)
    syms = ['a0:3']
    for i in xrange(3):
        for j in xrange(3):
            if M[i,j] == 1:
                M_sym = syms[i]
            elif M[i,j] == 2:
                M_sym = 1 - syms[i]
    return M_sym

这很好用.我得到一个矩阵,我可以将它用于我需要的所有符号计算.

This works just fine. I get a matrix out, which I can use for all the symbolical calculations I need.

我的问题是现在我想以指定的参数值评估我的矩阵.通常我只会使用 .subs 属性.但是,由于现在用作矩阵条目的符号最初被定义为函数中的临时元素,因此我不知道如何调用它们.

My issue is that now I want to evaluate my matrix at specified parameter-value. Usually I would just use the .subs attribute. However, since the symbols, that are now used as entries in my matrix, were originally defined as temporary elements in a function, I don't know how to call them.

这似乎应该是可能的,因为我能够执行符号计算.

It seems as if it should be possible, since I'm able to perform symbolic calculations.

我想做的事情看起来像(按照上面的代码):

What I want to do would look something like (following the code above):

M_sym = make_matrix(M)
M_eval = M_sym.subs([(a0,.8),(a1,.3),(a2,.5)])

但我得到的只是名称 'a0' 未定义".

But all I get is "name 'a0' is not defined".

如果有人提出解决方案,我会非常高兴!

I'd be super happy if someone out there got a solution!

附注.我不只是全局定义符号,因为在实际问题中我不知道我时不时有多少参数.

PS. I'm not just defining the symbols globally, because in the actual problem I don't know how many parameters I have from time to time.

推荐答案

符号由其名称定义.Sympy 会将具有相同名称的两个符号视为同一事物.因此,如果您知道所需符号的名称,只需使用 symbols 重新创建它们.

Symbols are defined by their name. Two symbols with the same name will considered to be the same thing by Sympy. So if you know the name of the symbols you want, just create them again using symbols.

您还可以很好地使用 Python 的 zip 函数.

You may also find good use of the zip function of Python.

这篇关于SymPy - 替换矩阵中的符号条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆