Reputation: 1056
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 here.
For clarification, I am interested in the actual assignment properties of sphere()
. Namely I am interested in knowing how to write
[X,Y,Z]=sphere(200)
In R.
Upvotes: 1
Views: 119
Reputation: 226182
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.
Take 2: return a list of 3, (n+1 x n+1) matrices.
sphere <- function(n) {
dd <- expand.grid(theta = seq(0, 2*pi, length.out = n+1),
phi = seq(-pi, pi, length.out = n+1))
with(dd,
list(x = matrix(cos(phi) * cos(theta), n+1),
y = matrix(cos(phi) * sin(theta), n+1),
z = matrix(sin(phi), n+1))
)
}
This will return a list of matrices with names x, y, z, not assign values to variables in the calling environment ... that's difficult/non-idiomatic in R.
Upvotes: 3
Reputation: 173813
This looks fairly similar to spheresurf3D
from the plot3D
package
library(plot3D)
spheresurf3D(bty = "b", ticktype = "detailed", phi = 30, theta = 135,
shade = 0.5, border = "black", col = jet.col()[1:75])
Upvotes: 2