geom
geom

Reputation: 195

How to write a function with symbolic vectors as arguments in sympy?

I want to write a function in sympy that takes as arguments two symbolic vectors and returns their inner product, e.g:

import sympy as sy
sy.init_printing()
phi = sy.symbols("phi")
v1 = sy.Matrix([sy.cos(phi),sy.sin(phi),0])
v2 = sy.Matrix([-sy.sin(phi),sy.cos(phi),0])

How do I declare a function:

fun = sy.Function("fun")

of two arguments like v1,v2 that returns their inner product.

Upvotes: 0

Views: 671

Answers (1)

JohanC
JohanC

Reputation: 80449

You can write this kind of functions just like ordinary Python functions. Whenever a SymPy object is encountered in an operation, the rest of the functions are automatically converted to SymPy equivalents.

sy.Function is for unknown functions, for example when involved in differential equations.

import sympy as sy
phi = sy.symbols("phi")
v1=sy.Matrix([sy.cos(phi),sy.sin(phi),0])
v2=sy.Matrix([-sy.sin(phi),sy.cos(phi),0])
v3=sy.Matrix([sy.cos(phi),sy.sin(phi),0])
v4=sy.Matrix([sy.sin(phi),sy.cos(phi),0])

def fun(v1, v2):
    assert isinstance(v1, sy.Matrix) and v1.shape[1] == 1
    assert isinstance(v2, sy.Matrix) and v2.shape[1] == 1 and v1.shape == v2.shape
    return sy.simplify(sum([v1[i]*v2[i] for i in range(v1.shape[0])])

print (fun(v1, v2))
print (fun(v1, v1))
print (fun(v3, v4))

Outputs:

0
1
2*sin(phi)*cos(phi)

Upvotes: 1

Related Questions