Sympy:提取矩阵的下三角部分
我正在尝试提取Sympy矩阵的下部三角形部分。由于我找不到Sympy中的tril
方法,因此我定义了:
def tril (M):
m = M.copy()
for row_index in range (m.rows):
for col_index in range (row_index + 1, m.cols):
m[row_index, col_index] = 0
return (m)
它似乎有效:
“>
.copy()
确保原始矩阵完整性的推荐方法吗?
I am trying to extract the lower triangular part of a SymPy matrix. Since I could not find a tril
method in SymPy, I defined:
def tril (M):
m = M.copy()
for row_index in range (m.rows):
for col_index in range (row_index + 1, m.cols):
m[row_index, col_index] = 0
return (m)
It seems to work:
Is there a more elegant way to extract the lower triangular part of a SymPy matrix?
Is .copy()
the recommended way to ensure the integrity of the original matrix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 SymPy 中,
M.lower_triangle(k)
将给出第 k 个对角线下方的下三角元素。默认值为k=0
。In SymPy,
M.lower_triangular(k)
will give the lower triangular elements below the kth diagonal. The default isk=0
.另一个答案建议使用 np.tril 函数:
由于符号的原因,它将 M 转换为 numpy 数组 - 对象数据类型。结果也是一个 numpy 数组。
您的函数返回一个
sympy.Matrix
。作为一般规则,混合
sympy
和numpy
会导致混乱,甚至错误。numpy
最适合数字工作。它可以处理诸如符号之类的非数字对象,但数学运算却是偶然的。np.tri...
函数基于np.tri
函数构建:我们可以由此创建一个符号矩阵:
并进行逐元素乘法:
np.tri 的工作原理是将列数组与行进行比较:
另一个答案建议
lower_triangle
。查看它的代码很有趣:它对每个元素应用
i>=j
测试。_new
必须迭代行和列。The other answer suggest using the
np.tril
function:That converts
M
into anumpy
array - object dtype because of the symbols. And the result is also a numpy array.Your function returns a
sympy.Matrix
.As a general rule mixing
sympy
andnumpy
leads to confusion, if not errors.numpy
is best for numeric work. It can handle non-numeric objects likesymbols
, but the math is hit-or-miss.The
np.tri...
functions are built on thenp.tri
function:We can make a symbolic Matrix from this:
and do element-wise multiplication:
np.tri
works by comparing a column array with a row:Another answer suggests
lower_triangular
. It's interesting to look at its code:It applies an
i>=j
test to each element._new
must be iterating on the rows and columns.您可以简单地使用 numpy 函数:
*当然,如下所述,您应该转换回 sympy.Matrix(np.tril(M)) 。但这取决于你接下来要做什么。
You can simply use numpy function:
*of course, as noted below, you should convert back to
sympy.Matrix(np.tril(M))
. But it depends on what you're going to do next.