如何使用Sympy得出关于Matrix元素的信息 [英] How to derive with respect to a Matrix element with Sympy

查看:170
本文介绍了如何使用Sympy得出关于Matrix元素的信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出矩阵和向量的积

A.v

A的形状为(m,n),v为暗n,其中m和n是符号,我需要针对矩阵元素计算导数. 我还没有找到使用适当向量的方法,所以我从2 MatrixSymbol开始:

with A of shape (m,n) and v of dim n, where m and n are symbols, I need to calculate the Derivative with respect to the matrix elements. I haven't found the way to use a proper vector, so I started with 2 MatrixSymbol:

n, m = symbols('n m')
j = tensor.Idx('j')
i = tensor.Idx('i')
l = tensor.Idx('l')
h = tensor.Idx('h')
A = MatrixSymbol('A', n,m)
B = MatrixSymbol('B', m,1)
C=A*B

现在,如果我尝试使用索引从A的元素之一中导出,我会得到未评估的表达式:

Now, if I try to derive with respect to one of A's elements with the indices I get back the unevaluated expression:

diff(C, A[i,j])
>>>> Derivative(A*B, A[i, j])

如果我也在C中引入索引(它不会让我仅在结果向量中使用一个索引),我将得到以Sum表示的乘积:

If I introduce the indices in C also (it won't let me use only one index in the resulting vector) I get back the product expressed as a Sum:

C[l,h]
>>>> Sum(A[l, _k]*B[_k, h], (_k, 0, m - 1))

如果相对于矩阵元素派生此结果,则最终得到0而不是带有KroneckerDelta的表达式,这就是我想要得到的结果:

If I derive this with respect to the matrix element I end up getting 0 instead of an expression with the KroneckerDelta, which is the result that I would like to get:

diff(C[l,h], A[i,j])
>>>> 0

我想知道也许我不应该从MatrixSymbols开始.我应该如何去实现我想要的行为?

I wonder if maybe I shouldn't be using MatrixSymbols to start with. How should I go about implementing the behaviour that I want to get?

推荐答案

SymPy的git版本(以及下一个版本)可以更好地解决此问题:

The git version of SymPy (and the next version) handles this better:

In [55]: print(diff(C[l,h], A[i,j]))
Sum(KroneckerDelta(_k, j)*KroneckerDelta(i, l)*B[_k, h], (_k, 0, m - 1))

这篇关于如何使用Sympy得出关于Matrix元素的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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