Python中矩阵元素的双重求和 [英] Double summation of matrix elements in Python
问题描述
基于下面的简化示例
我想要我的代码
from sympy import*
import numpy as np
init_printing()
x, y = symbols('x, y')
mat = Matrix([[x,1],[1,y]])
X = [1, 2, 3]
Y = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
将符号x
和y
替换为X
和Y
值,并且当然会计算给定矩阵的两倍总和.
to substitute the symbolic x
and y
with values of X
and Y
and ofcourse calculate the double summation of the given matrix.
我正在尝试解决这个问题,但是在每个步骤中我都遇到了麻烦. 任何帮助将不胜感激.
I'm trying to solve this but I'm having a rough time with the substitution in each step. Any help would be highly appreciated.
推荐答案
您已经导入了SymPy和NumPy,因此可以在此处选择工具.对于将一堆数字矩阵相加的工作,numpy是正确的工具.这是在numpy中求和的方式:
You've imported both SymPy and NumPy, so you have a choice of tools here. And for the job of adding together a bunch of numeric matrices, numpy is the right tool. Here is how the summation happens in numpy:
sum([sum([np.array([[x,1], [1,y]]) for y in yr]) for x, yr in zip(X,Y)])
这里yr代表Y的一行元素.外部的总和超过i索引,内部的总和超过j,尽管列表理解消除了将它们拼出的必要.
Here yr stands for a row of elements of Y. The outer sum is over i index, the inner is over j, although the list comprehension eliminates the need to spell them out.
结果是一个NumPy数组:
The result is a NumPy array:
array([[ 18, 9],
[ 9, 450]])
,但是您只需将Matrix()
放在它周围,就可以将其转换为SymPy矩阵:
but you can turn it into a SymPy matrix just by putting Matrix()
around it:
Matrix(sum([sum([np.array([[x,1], [1,y]]) for y in yr]) for x, yr in zip(X,Y)]))
这篇关于Python中矩阵元素的双重求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!