How to perform matrix by vector multiplication with sympy?
Asked Answered
C

2

6

I have:

  • a vector of type <class 'sympy.vector.vector.VectorMul'>; and
  • a matrix of type <class 'sympy.matrices.dense.MutableDenseMatrix'>

I would like to multiply the matrix by the vector in order to produce a vector.

Can I perform this operation conveniently or do I need to do some extra manipulation first?

For reference I am attempting to get the symbolic result of a rotation matrix applied to a vector.

Also below, is some of my code that deals with the above matrix and vector.

from sympy.vector import CoordSys3D

σ, θ, γ, λ, a, b, c = symbols('σ, θ, γ, λ, a, b, c, a_v, b_v, c_v')
σ = sin(θ)
γ = cos(θ)
λ = 1 - γ

N = CoordSys3D('N')
u = a*N.i + b*N.j + c*N.k # Axis of rotation

R = Matrix([
    [a*a*λ + γ, a*b*λ-c*σ, a*c*λ+b*σ],
    [b*a*λ+c*σ, b*b*λ + γ, b*c*λ-a*σ],
    [c*a*λ-b*σ, c*b*λ+a*σ, c*c*λ + γ],
])

# Input vector prior to rotation
v = a_v*N.i + b_v*N.j + c_v*N.k

# How to calculate the post rotation output vector w = Rv?

In summary is there a built-in mechanism in sympy for matrix by vector multiplication?

Cockleshell answered 20/2, 2019 at 3:0 Comment(1)
Just found this, docs.sympy.org/latest/_modules/sympy/vector/… which seems to be the opposite of what is required in this case. Is there a vector_to_matrix function?Cockleshell
C
4

Although I didn't find a function to do what I wanted, this code achieved the same result. I'm posting it here in case it is useful for others.

w = R * Matrix([v.coeff(N.i), v.coeff(N.j), v.coeff(N.k)])
Cockleshell answered 20/2, 2019 at 3:43 Comment(0)
P
2

In the current version of SymPy (1.11), you can calculate the vector matrix product by using the matmul operator (@)

The following code works for me:

v = Matrix([x, y, z])
Kx = Matrix([[1,        0,        0      ], 
             [0,        cos(kx), -sin(kx)], 
             [0,        sin(kx),  cos(kx)]])

product = Kx @ v


# Don't:
# product = v @ Kx
Pointdevice answered 17/1, 2023 at 14:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.