SymPy 矩阵列表的总和 [英] Sum of a list of SymPy matrices

查看:35
本文介绍了SymPy 矩阵列表的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 python 列表包含 sympy 矩阵对象,我需要将它们全部求和.如果所有列表元素都只是符号,那么在 python 中使用内置 sum 函数就可以了.

import sympy as spx = sp.symbols('x')ls = [x, x+1, x**2]打印(总和(ls))>>>x**2 + 2*x + 1

但是对于矩阵类型的元素,求和函数看起来不起作用.

import sympy as spls = [sp.eye(2), sp.eye(2)*5, sp.eye(2)*3]打印(总和(ls))>>>类型错误:无法添加 和 <class 'int'>

我该如何解决这个问题?

解决方案

这就是为什么 Python 的 sum 函数 有一个可选的开始"参数:所以你可以用你添加的那种零对象"来初始化它.在这种情况下,使用零矩阵.

<预><代码>>>>打印(总和(ls,sp.zeros(2)))矩阵([[9, 0], [0, 9]])

My python list contains sympy matrix object, and I need to sum them all. If all list elements are just symbols, then using built-in sum function in python works fine.

import sympy as sp
x = sp.symbols('x')
ls = [x, x+1, x**2]
print(sum(ls))

>>> x**2 + 2*x + 1

But for the elements of matrix type, sum function looks not working.

import sympy as sp
ls = [sp.eye(2), sp.eye(2)*5, sp.eye(2)*3]
print(sum(ls))

>>> TypeError: cannot add <class 'sympy.matrices.dense.MutableDenseMatrix'> and <class 'int'>

How can I resolve this problem?

解决方案

This is why Python's sum function has an optional "start" argument: so you can initialize it with a "zero object" of the kind you are adding. In this case, with a zero matrix.

>>> print(sum(ls, sp.zeros(2)))
Matrix([[9, 0], [0, 9]])

这篇关于SymPy 矩阵列表的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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