2
\$\begingroup\$

I wrote some very basic R code.

This has at least two problems.

  1. It uses a very basic imperative-programming style instead of good R style.

  2. It draws the result as an ellipse, not a circle. This effect is barely visible on RGui on Windows, but extremely visible in RStudio on Linux. [Edit: rcs has mentioned that the asp parameter of the image command can fix this. Thanks, rcs.]

There are some debatable issues. For example, there is no good reason why I draw the radius at the distance that I do, so I consider this to be a "magic" number, and I try to avoid "magic numbers" in code because they cause maintenance problems. The number is in there because I don't think it's worthwhile specifying a user input or a function argument to control it.

edge<-100
magicradius=.81
magicmargin=.01
width<-(2*edge)+1

x<-c(-edge:edge)
y<-c(-edge:edge)

squarelist<-c(1:((width^2)))

dim(squarelist)<-c(width, width)

counter<-0
for (i in 1:length(x)){
  for (j in 1:length(y)){
    counter<-counter+1
    if( (((magicradius-magicmargin)*(edge))<sqrt( x[i]^2 + y[j]^2  ) )
        &(((magicradius+magicmargin)*(edge))>sqrt( x[i]^2 + y[j]^2 ) ) ){
      squarelist[counter]<-sqrt( x[i]^2 + y[j]^2)
    } else {
      squarelist[counter]<-0

    }      
  }
}

gg<-matrix(squarelist,nrow=width,ncol=width)

image(gg)
\$\endgroup\$
  • 1
    \$\begingroup\$ fix for Problem 2: image(gg, asp=1) \$\endgroup\$ – rcs Nov 21 '13 at 21:19
3
\$\begingroup\$

A vectorized solution using outer (Outer Product of Arrays):

edge <- 100
magicradius <- .81
magicmargin <- .01
width <- (2*edge) + 1

x <- -edge:edge
y <- -edge:edge

mat <- outer(x, y, function(x,y) sqrt(x^2 + y^2))
ind <- mat > ((magicradius-magicmargin)*edge) &
       mat < ((magicradius+magicmargin)*edge)
image(ind, asp=1)

enter image description here

The aspect ratio in image() can be set with the asp argument (see the Details section in ?plot.window)

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I had not been aware of the outer() syntax until now --thanks. The ind construction is obviously much easier to write than mine and should result in shorter code. \$\endgroup\$ – dataqeuerent Nov 25 '13 at 3:11
  • \$\begingroup\$ I have just tested the above code in rstudio and it produces unexpected results. \$\endgroup\$ – dataqeuerent Nov 25 '13 at 3:46
  • \$\begingroup\$ The output produced by gg seems to be very different from the output produced by ind. \$\endgroup\$ – dataqeuerent Nov 25 '13 at 6:37
  • \$\begingroup\$ my code produces exactly the same result as your example. \$\endgroup\$ – rcs Nov 25 '13 at 8:03
  • \$\begingroup\$ See here r-fiddle.org/#/fiddle/wk5fEVOu \$\endgroup\$ – rcs Nov 25 '13 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.