Double summation of matrix elements in Python

我只是一个虾纸丫 提交于 2019-12-10 19:06:38

问题


Based on the simplified example below

I would like in my code

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]]

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.


回答1:


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)])

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.

The result is a NumPy array:

 array([[ 18,   9],
       [  9, 450]])

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)]))


来源:https://stackoverflow.com/questions/37468787/double-summation-of-matrix-elements-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!