'matrix multiply elementwise

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



Solution 1:[1]

What you are looking for is the Hadamard product (or Schur product).

In sympy it is available as sympy.matrices.dense.matrix_multiply_elementwise(A, B), documented here.

Solution 2:[2]

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?

Solution 3:[3]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 laolux
Solution 2 Sci Prog
Solution 3 EAzevedo