1
$\begingroup$

I would like to iterate over a nested list of the following format:

q={{1,{r1,t1,p1},{}},{2,{r2,t2,p2},{}}}

where r,t and p are numbers (spherical coordinates).

In the empty sublists I would like to enter the cartesian coordinates {x,y,z}, so that the list looks like:

q={{1,{r1,t1,p1},{x1,y1,z1}},{2,{r2,t2,p2},{x2,y,z2}}}

I have done this with a Do-loop and it works, but since I'm experimenting with functional programming, I was wondering if this would be achievable by using Map (or a similar function).

Of course mapping the FromSphericalCoordinates-Function to the spherical coordinates (in sub-list #2) works, but how could I update the empty sub-list #3 for the cartesian coordinates?

Any idea whether and how this works?

$\endgroup$

4 Answers 4

2
$\begingroup$

Using ReplacePart:

q = {{1, {r1, t1, p1}, {}}, {2, {r2, t2, p2}, {}}}
ReplacePart[#, 
   3 -> CoordinateTransform[ "Spherical" -> "Cartesian", #[[2]]]] & /@
  q

or

ReplacePart[#, 3 -> FromSphericalCoordinates[#[[2]]]] & /@ q

{{1, {r1, t1, p1}, {r1 Cos[p1] Sin[t1], r1 Sin[p1] Sin[t1], r1 Cos[t1]}}, {2, {r2, t2, p2}, {r2 Cos[p2] Sin[t2], r2 Sin[p2] Sin[t2], r2 Cos[t2]}}}

$\endgroup$
1
$\begingroup$

There are a number of ways to do this, e.g.

  • Built-in function CoordinateTransform

      q = {{1, {r1, t1, p1}, {}}, {2, {r2, t2, p2}, {}}}
      {#1, #2, CoordinateTransform["Spherical" -> "Cartesian", #2]} & @@@ q
    
  • Define transform yourself and use Map

    f[{a_, b_, ___}] := {a, b, 
    b[[1]] {Sin[b[[2]]] Cos[b[[3]]], Sin[b[[2]]] 
    Sin[b[[3]]], Cos[b[[2]]]}}
    f /@ q
    

Both yield:

{{1, {r1, t1, p1}, {r1 Cos[p1] Sin[t1], r1 Sin[p1] Sin[t1], 
   r1 Cos[t1]}}, {2, {r2, t2, p2}, {r2 Cos[p2] Sin[t2], 
   r2 Sin[p2] Sin[t2], r2 Cos[t2]}}}

Comments:

  • there are many ways to do this
  • the empty lists are unnecessary (for this purpose)
  • you need to check transform conforms with your spherical coordinates convention
$\endgroup$
1
$\begingroup$

If you want to map then

q[[All, 3]] = FromSphericalCoordinates /@ q[[All, 2]]; q

$\endgroup$
0
$\begingroup$

Just a little pattern matching using ReplaceAll (Map not needed):

q /. {num_, sc_, _} :> {num, sc, FromSphericalCoordinates[sc]}

yields

{{1, {r1, t1, p1}, {r1 Cos[p1] Sin[t1], r1 Sin[p1] Sin[t1], r1 Cos[t1]}},
 {2, {r2, t2, p2}, {r2 Cos[p2] Sin[t2], r2 Sin[p2] Sin[t2], r2 Cos[t2]}}}
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.