3D Sine Wave

[This article was first published on StaTEAstics., and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Had a headache last night, so decided to take things easy and just read posts Google+. Then I came across this post which seems interesting so I thought I would play around before I head to bed.

First of all, I thought generating a square base would be much easier in R compare to hexagons. Starting with 2 numeric vectors and then expand them by expand.grid() would do the job. The next step is to provide the rotation, this is also rather simple since it can be achieved by multiplying the following matrix.

[ R = begin{bmatrix} cos theta & -sin theta \ sin theta & cos theta \ end{bmatrix} ]

Finally, the last step is to define the wave. This is done by a sine function with the phase being the distance away from the center.

[ d = sqrt{x^2 + y^2}\ y_t = y_t + 10 times sin(t + d) ]

And here is the code, enjoy....

<br /><br />library(animation)<br /><br />## Create the square to start with<br />x = seq(-5, 5, length = 50)<br />y = seq(-5, 5, length = 50)<br />square = as.matrix(expand.grid(x, y))<br /><br />## Create the rotation matrix<br />angle = pi/180<br />rotation =<br />    matrix(c(cos(angle), -sin(angle), sin(angle), cos(angle)), ncol = 2)<br /><br />## Plot<br />saveGIF(<br />    {<br />        init = square<br />        for(i in seq(0, 2 * pi, length = 360)){<br />            tmp = init<br />            distFromCenter = sqrt(tmp[, 1]^2 + tmp[, 2]^2)<br />            tmp[, 2] = tmp[, 2] + 10 * sin(i - distFromCenter)<br />            colIntensity = (tmp[, 2] + abs(min(tmp[, 2])))/<br />                max((tmp[, 2] + abs(min(tmp[, 2]))))<br />            plot(tmp[, c(1, 2)], xlim = c(-10, 10), ylim = c(-20, 20),<br />                 pch = ".", cex = 3, axes = FALSE, xlab = "", ylab = "",<br />                 col = rgb(colIntensity, 0, 0))            <br />            init = init %*% rotation<br />        }<br />    },<br />    movie.name = "./wave.gif", interval = 0.005,<br />    nmax = 30, ani.width = 800,  ani.height = 800<br />    )<br /><br />

To leave a comment for the author, please follow the link and comment on their blog: StaTEAstics..

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)