falematte
falematte

Reputation: 147

Vector not defined by components in sympy

Is it possible in the Sympy vector package to initialize a vector without having to declare its components? Often when we do symbolic calculations it is not required to explicitate components.

Upvotes: 2

Views: 434

Answers (1)

user6655984
user6655984

Reputation:

The Vector objects in Vector module always have three slots for components, which have to be filled with numeric or symbolic expressions. If you don't want to provide the names of components, matrix_to_vector can be used, passing a list of freshly created symbols to fill the slots.

from sympy import symbols
from sympy.vector import CoordSys3D, matrix_to_vector
N = CoordSys3D("N")
v = matrix_to_vector(symbols("v_1:4"), N)

Now v is a vector with components v_1, v_2, v_3.


In another direction, one can do linear algebra using Matrix Expressions, representing vectors as matrices with one column. This conforms better to the idea of manipulating vectors without listing their components

from sympy import MatrixSymbol
v  = MatrixSymbol("v", 3, 1)
A = MatrixSymbol("A", 3, 3)
print(A*v)  # simply A*v 
(A*v).as_explicit()   # print out in components

prints

Matrix([
[A[0, 0]*v[0, 0] + A[0, 1]*v[1, 0] + A[0, 2]*v[2, 0]],
[A[1, 0]*v[0, 0] + A[1, 1]*v[1, 0] + A[1, 2]*v[2, 0]],
[A[2, 0]*v[0, 0] + A[2, 1]*v[1, 0] + A[2, 2]*v[2, 0]]])

Upvotes: 1

Related Questions