# [R] code optimization tips

baptiste Auguié ba208 at exeter.ac.uk
Mon Jul 23 16:45:06 CEST 2007

```Thanks for your reply,

On 23 Jul 2007, at 15:19, jim holtman wrote:

> First question is why are you defining the functions within the main
> function each time?  Why don't you define them once outside?
>

Fair enough!

As said, I'm new to R and don't know whether it is best to define
functions outside and pass to them all necessary arguments, or nest
them and get variables in the scope from parents. In any case, I'd
agree my positions(), mod() and sij() functions would be better
outside. Here is a corrected version (untested as something else is
running),

>
> positions <- function(N) {
>    reps <- 2*N+1
>    matrix(c(rep(-N:N, each = reps), rep(-N:N, times = reps)),
>           nrow = 2, byrow = TRUE)
> }

> mod<-function(x){sqrt(x[1]^2+x[2]^2)} # modulus

> sij <-function(rj,ri,k){
> rij=mod(rj-ri)
> cos_ij=rj[1]/rij
> sin_ij=rj[2]/rij
>
> A<-(1-1i*k*rij)*(3*cos_ij^2-1)*exp(1i*k*rij)/(rij^3)
> B<-k^2*sin_ij^2*exp(1i*k*rij)/rij
>
> sij<-A+B
> }

> alpha_c <- function(lambda=600e-9,alpha_s=1e-14,N=400,spacing=1e-7){
>
> k<-2*pi/lambda
> ri<-c(0,0) # particle at the origin
>
> rj<-positions(N)*spacing # all positions in the 2N x 2N array
> rj<-rj[1:2,-((dim(rj)[2]-1)/2+1)] # remove rj=(0,0)
>
> s_ij<-apply(rj,2,sij)

*** Now, how do I pass k and ri to this function ? ***

> S<-sum(s_ij)
> alpha_s/(1-alpha_s*S)
> }
> alpha_c()
>

>
> --
> Jim Holtman
> Cincinnati, OH
> +1 513 646 9390
>
> What is the problem you are trying to solve?

Wondering whether that's part of the signature?

the problem is related to scattering by arrays of particles, more
specifically to evaluate the array influence on the effective
polarizability (alpha) of a particle via dipolar radiative coupling.

```