5

I translated the MATLAB cart2sph and sph2cart functions to python in this way.

import numpy as np

def cart2sph(x,y,z):
    azimuth = np.arctan2(y,x)
    elevation = np.arctan2(z,np.sqrt(x**2 + y**2))
    r = np.sqrt(x**2 + y**2 + z**2)
    return azimuth, elevation, r

def sph2cart(azimuth,elevation,r):
    x = r * np.cos(elevation) * np.cos(azimuth)
    y = r * np.cos(elevation) * np.sin(azimuth)
    z = r * np.sin(elevation)
    return x, y, z

I didn't find any library in numpy that translate the MATLAB change of coordinates so I write them for my self. Is there in numpy a more efficient way in terms of execution time to write this fuctions?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
overcomer
  • 2,244
  • 3
  • 26
  • 39
  • 2
    Have you looked at this? http://stackoverflow.com/questions/4116658/faster-numpy-cartesian-to-spherical-coordinate-conversion – rayryeng May 06 '15 at 18:02
  • 3
    You can gain a small amount of speed by factoring out some terms that are used more than once, e.g. `xy2 = x**2 + y**2; elev = atan2(z,sqrt(xy2)); r = sqrt(xy2 + z**2)`. Also `cos(elevation)` needs to be computed only once. – Bas Swinckels May 06 '15 at 21:30
  • 1
    I added an optimized Numexpr solution and some execution time comparison in the https://stackoverflow.com/a/30185737/1791279 question as pointed out by @rayryeng The implementation of `sph2cart` can be done with the same logic. – rth May 12 '15 at 08:41

0 Answers0