mcluka
mcluka

Reputation: 285

Double summation of matrix elements in Python

Based on the simplified example below

enter image description here

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.

Upvotes: 3

Views: 1848

Answers (1)

user3717023
user3717023

Reputation:

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

Upvotes: 4

Related Questions