Home > Software engineering >  What is the R equivalent of Matlab's `sphere()` function
What is the R equivalent of Matlab's `sphere()` function

Time:11-07

I am trying to replicate some Matlab code in R and I have been looking around for an R equivalent of Matlab's sphere() function.

For reference the sphere() function documentation is enter image description here

CodePudding user response:

How about:

library(geometry)
sphere <- function(n) {
   dd <- expand.grid(theta = seq(0, 2*pi, length.out = n 1)[-1],
                     phi = seq(-pi, pi, length.out = n 1)[-1])
   sph2cart(dd$theta, dd$phi, r = 1)
}

Really you don't need the geometry package either, as the payload of geometry::sphere2cart is just

x <- r * cos(phi) * cos(theta)
y <- r * cos(phi) * sin(theta)
z <- r * sin(phi)

The other 20-odd lines of code are argument-processing and error-checking. So you could put together your own self-contained function using just expand.grid and the three lines of geometry.

Note that sph2cart (and hence the function above) returns a three-column matrix; I assume that [X,Y,Z] does automatic unpacking of the results into three separate variables (as in Python tuple-unpacking). R doesn't have a similarly convenient syntax.

  • Related