如何在SymPy中用矢量替换矩阵的对角线元素

如何在SymPy中用矢量替换矩阵的对角线元素

本文介绍了如何在SymPy中用矢量替换矩阵的对角线元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量X,它是这样创建的:

I have a vector X which I created like this:

from sympy import *

x1 = Symbol('x1')
x2 = Symbol('x2')
x3 = Symbol('x3')

X = Matrix([x1, x2, x3])

然后我还有一个矩阵myMat,其中仅包含一个:

Then I also have a matrix myMat which just contains ones:

myMat = ones(3, 3)

Matrix([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])

现在我想用我的向量X替换矩阵的对角线;我想要的结果看起来像这样:

Now I would like to replace the diagonal of the matrix by my vector X; my desired outcome looks like this:

Matrix([
[x1, 1, 1],
[1, x2, 1],
[1, 1, x3]])

我当然可以在for-loop中做到这一点:

I can of course do it in a for-loop like this:

for ind, el in enumerate(X):
    myMat[ind, ind] = el

但我想知道是否存在通过直接访问此矩阵的对角线来实现此目的的更明智的方法.虽然我可以计算矩阵的trace,但我找不到使用myMat.diag = X之类的元素替换对角线元素的方法.有办法吗?

but I am wondering whether there is a smarter way of doing that by directly accessing the diagonal of this matrix. While I can calculate the trace of the matrix, I could not find a way to replace just the diagonal elements using something like myMat.diag = X. Is there a way of doing that?

编辑

@Emilien使我步入正轨,因此我接受了此答案.在此答案的基础上,我还发布了自己的解决方案,该解决方案使用sympynumpy并在一行中解决了该问题:

@Emilien got me on the right track and therefore I accepted this answer. Building up on this answer, I also posted my own solution which makes use of sympy and numpy and solves the problem in one single line: my answer

推荐答案

您可以使用对角线矩阵和恒等矩阵来构建它,但我不确定它在性能方面有何优势,但也许更容易理解如果您正在寻找代码,那么请阅读该代码.

You can build it with diagonal and identity matrices, I'm not sure it's much better on a performance point of vue thought, but maybe it's easier to understand when reading the code if that's what you're looking for.

x1, x2, x3 = symbols('x1 x2 x3')
mat = diag(x1,x2,x3)-eye(3)+ones(3)

l = symbols('x1 x2 x3')
mat = diag(*l)-eye(3)+ones(3)

如您所愿.

另一种棘手的解决方案,也许可读性较差:

Another tricky solution, maybe less readable:

l = symbols('x1 x2 x3')
Matrix(3, 3, lambda i,j: l[i] if i==j else 1)

最后,如果您不想修改原始文件

Finally, if you do not wish to modify the original

l = symbols('x1 x2 x3')
M = Matrix(([1,2,3],[4,5,6],[7,8,9]))
M = Matrix(3, 3, lambda i,j: l[i] if i==j else M[i,j])

这篇关于如何在SymPy中用矢量替换矩阵的对角线元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:20