How to do dot/cross multiplication of Vectors with Sympy

11,112

Solution 1

numpy is designed for this, it is a clean and fast way to do numerical calculations because it's implemented in C.

In [36]: x = [1, 2, 3]
    ...: y = [4, 5, 6]

In [37]: import numpy as np
    ...: print np.dot(x, y)
    ...: print np.cross(x, y)
    ...: print np.add(x, y) #np.subtract, etc.
32
[-3  6 -3]
[5 7 9]

There is a discussion on numpy and sympy on google groups.

Solution 2

http://docs.sympy.org/0.7.2/modules/physics/mechanics/api/functions.html

There are examples on that doc and some code here. What exactly don't you understand? Maybe, try to be more specific.

The dot multiplication as you write it is explained in the doc with that example:

from sympy.physics.mechanics import ReferenceFrame, Vector, dot
from sympy import symbols
q1 = symbols('q1')
N = ReferenceFrame('N') # so, ||x|| = ||y|| = ||z|| = 1
dot(N.x, N.x)
1 # it is ||N.x||*||N.y||*cos(Nx,Ny)
dot(N.x, N.y)
0 # it is ||N.x||*||N.y||*cos(Nx,Ny)
A = N.orientnew('A', 'Axis', [q1, N.x])
dot(N.y, A.y)
cos(q1)

Also, you might consider doing it with numpy...

Solution 3

To do vector dot/cross product multiplication with sympy, you have to import the basis vector object CoordSys3D. Here is a working code example below:

from sympy.vector import CoordSys3D
N = CoordSys3D('N')
v1 = 2*N.i+3*N.j-N.k
v2 = N.i-4*N.j+N.k
v1.dot(v2)
v1.cross(v2)
#Alternately, can also do
v1 & v2 
v1 ^ v2

Please note the last 2 lines are not recommended by sympy documentation. It is better to use the methods explicitly. Personally I think this is a matter of preference, however.

Solution 4

You can do it as described here: https://docs.sympy.org/latest/modules/matrices/matrices.html?highlight=cross#sympy.matrices.matrices.MatrixBase.cross

For example:

>>> from sympy import Matrix
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> v = Matrix([1, 1, 1])
>>> M.row(0).dot(v)
6
>>> M.col(0).dot(v)
12
>>> v = [3, 2, 1]
>>> M.row(0).dot(v)
10

Solution 5

If you have symbolic vectors and need to use sympy it is actually very simple, just use the cross function as exemplified below:

import sympy as s
a,b,c,x,y,z = s.symbols("a,b,c,x,y,z")
v1 = s.Matrix([a,b,c])
v2 = s.Matrix([x,y,z])
cross_result = v1.cross(v2)
print(cross_result)

With output:

Matrix([
[ b*z - c*y],
[-a*z + c*x],
[ a*y - b*x]])
Share:
11,112
Vannen
Author by

Vannen

Updated on July 25, 2022

Comments

  • Vannen
    Vannen almost 2 years

    I would like to know how to do

    • dot multiplication
    • cross multiplication
    • add/sub

    of vectors with the sympy library. I have tried looking into the official documentation but I have had no luck or It was too complicated. Can anyone help me out on this?

    I was trying to do this simple operation

    a · b = |a| × |b| × cos(θ)