在 SymPy 中自动填充矩阵元素
有没有办法在 SymPy 中隐式定义符号矩阵的元素,遵循以下规则: symbol 后跟矩阵(或数字对)中的 subindices
例如,我想定义一个名为 M
的 3 x 2 矩阵,我希望 SymPy 自动创建它并将其填充为:
M =
[ M_11 M_12]
[ M_21 M_22]
[ M_31 M_32]
如果没有办法隐式执行此操作,那么最简单的方法是什么方法来做到这一点明确地(例如循环)?
Is there a way to implicitly define the elements of a symbolic matrix in SymPy following a rule such as: symbol followed by subindices in the matrix (or pairs of numbers)
For example, I would like to define a 3 x 2 matrix called M
, and I would like SymPy to automatically create it and populate it as:
M =
[ M_11 M_12]
[ M_21 M_22]
[ M_31 M_32]
If there is no way to do this implicitly, what would be the easiest way to do this explicitly (e.g. looping)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑使用 MatrixSymbol 而不是 Matrix 对象。
MatrixSymbol
表示矩阵,无需显式元素。Consider using the
MatrixSymbol
rather thanMatrix
object.MatrixSymbol
represents matrices without the need for explicit elements.像这样的事情怎么样:
编辑:我想我应该添加一个小解释。 sympy.Matrix() 的前两个参数将矩阵定义为 3x2(如您指定的)。第三个参数是一个lambda函数,它本质上是在一行中定义函数的简写方式,而不是使用def正式定义它。该函数将变量i和j作为输入,它们通常是矩阵的索引。对于传递到 lambda 的每对 (i,j) (即,对于矩阵的每个元素),我们创建一个新的符号变量 M_ij 。 sympy.var() 将字符串作为输入,定义新符号变量的名称。我们使用格式字符串 'M_%d%d' 即时生成此字符串,并用 (i+1,j+1) 填充它。我们将 1 添加到 i 和 j 中,因为您希望矩阵为 1 索引,而不是像 Python 中的标准那样为 0 索引。
How about something like this:
Edit: I suppose I should add a small explanation. The first two arguments to sympy.Matrix() are defining the matrix as 3x2 (as you specified). The third argument is a lambda function, which is essentially a shorthand way of defining a function in one line, rather than formally defining it with def. This function takes variables i and j as input, which conveniently are the indices of the matrix. For each pair (i,j) which are passed into the lambda (i.e., for each element of the matrix), we are creating a new symbolic variable M_ij. sympy.var() takes a string as input which defines the name of the new symbolic variable. We generate this string on-the-fly using the format string 'M_%d%d' and filling it with (i+1,j+1). We are adding 1 to i and j because you want the matrix to be 1-indexed, rather than 0-indexed as is the standard in Python.