matrix multiply elementwise

Viewed 3523

Is it possible to do from matrix_multiply_elementwise in sympy library with more than two matrices? Or any other way for multiplying couple of matrices elementwise?

p.s. In numpy it is straightforward but since I need high precision calculation I decided to use sympy

3 Answers

Here is a way to multiply three matrices elementwise. The solution can be generalized to more than three matrices, or to functions other than multiplication.

from sympy import Matrix, pprint

a = Matrix([[1,2],[3,4]])
b = Matrix([[1,10],[100,1000]])
c = Matrix([[-1,1],[1,-1]])
x = Matrix(2,2, lambda i,j,m1=a,m2=b,m3=c: m1[i,j]*m2[i,j]*m3[i,j])

pprint(a)
pprint(b)
pprint(c)
pprint(x)

For simplicity, this solution is for matrices of shape 2X2, but it could easily be adapted for other sizes (using the shape property)

Here is the output

⎡1  2⎤
⎢    ⎥
⎣3  4⎦
⎡ 1    10 ⎤
⎢         ⎥
⎣100  1000⎦
⎡-1  1 ⎤
⎢      ⎥
⎣1   -1⎦
⎡-1    20  ⎤
⎢          ⎥
⎣300  -4000⎦
Related