How to substitute symbol for matrix using symPy and numPy

后端 未结 1 1643
刺人心
刺人心 2021-01-12 18:18

I\'m trying to substitute two symbols in my equation for the matrix form of each of them.

I created a commutator function which formed my expression:



        
1条回答
  •  走了就别回头了
    2021-01-12 18:42

    Perhaps use lambdify:

    import sympy as sy
    import numpy as np    
    from sympy.abc import x, y
    
    z = ((x+y)**2).expand()
    print(z)
    # x**2 + 2*x*y + y**2
    X = np.arange(6).reshape(2,3)
    Y = np.arange(1,7).reshape(2,3)    
    
    f = sy.lambdify((x, y), z, 'numpy')
    print(f(X, Y))
    # [[  1   9  25]
    #  [ 49  81 121]]
    
    assert np.allclose(f(X, Y), (X**2 + 2*X*Y + Y**2))
    

    0 讨论(0)
提交回复
热议问题