Search code examples
pythonsympysymbolic-math

Expression as a function of symbols


I am new to using sympy so my question might be trivial.

I am trying to find a way to generate an expression as a function of other symbols.

To be more concise I have the following problem. I want to generate a symbolic representation of the relation between RPY-orientation angles and the rotation matrix produced by them. This is straight-forward. I can define an Rz(a) matrix,an Ry(b) and Rx(g) matrix and then compute their product

 Rz=Matrix([[cos(a),-sin(a),0],[sin(a),cos(a),0],[0,0,1]])
 Ry=Matrix([[cos(b),0,sin(b)],[0,1,0],[-sin(b),0,cos(b)]])
 Rx=Matrix([[1,0,0],[0,cos(g),-sin(g)],  [0,sin(pg),cos(pg)]])
 R=Rz*Ry*Rx

As expected R will be a complex matrix expression of a,b,g Now, suppose I want also to compute a rotation matrix for a second rotation, with different angles. I could copy the above code, using different symbols

 Rz1=Matrix([[cos(a1),-sin(a1),0],[sin(a1),cos(1a),0],[0,0,1]])
 Ry1=Matrix([[cos(b1),0,sin(b1)],[0,1,0],[-sin(b1),0,cos(b1)]])
 Rx1=Matrix([[1,0,0],[0,cos(g1),-sin(g1)],  [0,sin(g1),cos(g1)]])
 R1=Rz1*Ry1*Rx1

R1 would then be a complex expression of a1,b1,g1

I was wondering if there is a way to define a "symbolic function" that would produce the same result, by reusing the same code.

def SymRot(s1,s2,s3): = ...

so that

  SymRot(a,b,g) == R 
  SymRot(a1,b1,g1) == R1

where R and R1 are the expressions mentioned above


Solution

  • Unless I miss something, that is just a regular python function. Whose arguments happen to be symbols

    from sympy import Matrix, symbols, sin, cos
    
    def SymRot(a1, b1, g1):
        Rz=Matrix([[cos(a1),-sin(a1),0],[sin(a1),cos(a1),0],[0,0,1]])
        Ry=Matrix([[cos(b1),0,sin(b1)],[0,1,0],[-sin(b1),0,cos(b1)]])
        Rx=Matrix([[1,0,0],[0,cos(g1),-sin(g1)],  [0,sin(g1),cos(g1)]])
        return Rz*Ry*Rx
    
    a,b,g=symbols("a b g")
    R=SymRot(a,b,g)
    
    a1,b1,g1=symbols("a1 b1 g1")
    R1=SymRot(a1,b1,g1)
    

    Not 100% sure because there are some inconsistencies in your examples (you mention a symbol "pg" in the first version, that is not in the second. Not to mention the "1a" that is a lexical error. It would be easier if you posted copy&paste of code you actually ran)