Sympy get vector from vector field

Question:

I’m using sympy (which is awesome) and I just made a vector field like this

> import sympy
> from sympy.vector import CoordSys3D
> from sympy import *
> R = CoordSys3D('R')
> x, y, z, t = symbols('x y z t')
> v = x*R.i + 4*z*R.j + y*R.k
x*R.i + 4*z*R.j + y*R.k
> v.evalf(subs={x:6, y:5, z:2})
6.00000000000000*R.i + 8.00000000000000*R.j + 5.00000000000000*R.k

and what I need is to get a vector or list of the form [6.0,8.0,5.0], so is there a way to get a list form v.evalf()? I could use use split or something on "6.00000000000000*R.i + 8.00000000000000*R.j + 5.00000000000000*R.k" but thats seems ugly and maybe there a built in method for that?

Asked By: Fransebas

||

Answers:

In [252]: vector = v.evalf(subs={x:6, y:5, z:2}); vector
Out[252]: 6.00000000000000*R.i + 8.00000000000000*R.j + 5.00000000000000*R.k

In [253]: list(vector.to_matrix(R))
Out[253]: [6.00000000000000, 8.00000000000000, 5.00000000000000]

Other possibilities include

In [256]: vector.as_poly().coeffs()
Out[256]: [6.00000000000000, 8.00000000000000, 5.00000000000000]

In [257]: list(vector.components.values())
Out[257]: [5.00000000000000, 8.00000000000000, 6.00000000000000]

but I think they suffer a fatal flaw which is exposed when one or more of the components equal 0. For example, if z is set to 0:

In [258]: vector = v.evalf(subs={x:6, y:5, z:0}); vector
Out[258]: 6.00000000000000*R.i + 5.00000000000000*R.k

Then list(vector.to_matrix(R)) still returns 3 components:

In [259]: list(vector.to_matrix(R))
Out[259]: [6.00000000000000, 0, 5.00000000000000]

while these other two expressions omit the zero-component:

In [260]: vector.as_poly().coeffs()
Out[260]: [6.00000000000000, 5.00000000000000]

In [261]: list(vector.components.values())
Out[261]: [5.00000000000000, 6.00000000000000]
Answered By: unutbu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.