title: For loop not running as intended in R
body: <p>Good evening<br>
  I am currently working on a maximization problem using the nlminb() function in R. Heres part of the code. These are the initial input parameters</p>
  
  <pre><code>w &lt;- rnorm(12,0.5,1)
  y &lt;- 1:12
  x &lt;- rnorm(12,0,1)
  h &lt;- 0.25
  n &lt;- length(x)
  
  g &lt;- sd(x)
  </code></pre>
  
  <p>The first of two functions from which the parameters will be evaluated</p>
  
  <pre><code> Resid &lt;- function(par, data) 
      {
        alpha.0 &lt;- par[1] 
        alpha.1 &lt;- par[2]
        beta.1  &lt;- par[3]
        mu1     &lt;- par[4]
        mu2     &lt;- par[5]
  
    n &lt;- length(x)
    sigma.sqs &lt;- numeric(n) 
    epsilon &lt;- numeric(n) 
    sigma.sqs[1] &lt;- g 
    epsilon[1] = x[1] - mean(x)
    for(ii in c(1:(n-1))) {
      sigma.sqs[ii + 1] &lt;- (
        alpha.0 +  
          alpha.1 * (epsilon[ii])^2 +
          beta.1 * sigma.sqs[ii])
    epsilon[ii+1] &lt;- (x[ii+1]-mu1-mu2*x[ii])/sigma.sqs[ii]
  
      Ksum &lt;- 0
      for(j in (1:(n-1))){
        Ksum &lt;- Ksum + (((epsilon[ii]/(sigma.sqs[ii]^0.5))-w[j])/h)
      }
    }
  
    return(list(et = epsilon, ht = sigma.sqs, xt=Ksum)) 
  }
  </code></pre>
  
  <p>The second part, taking the sigma and epsilons from the function Resid</p>
  
  <pre><code> LogL &lt;- function(par, data) {
  
        res &lt;- Resid(par, data) 
        sigma.sqs &lt;- res$ht
    epsilon &lt;- res$et  
    f &lt;- res$xt
  
   return( 1/n * sum( log(1/(n*h)*(1/((2*pi)^0.5))*exp(-0.5*(f)^2)) +    log(1/(sigma.sqs^0.5))))
  
  }
  </code></pre>
  
  <p>and finally maximizing </p>
  
  <pre><code> o &lt;- nlminb(start=c(0.001,0.001,0.001,0.001,0.001), objective= LogL, lower=  0.0000001  ) 
      print(o)
  </code></pre>
  
  <p>The code runs, but its coming up with NaNs. The problem seems to be arising in the for-loop regaring </p>
  
  <pre><code>        Ksum &lt;- 0
          for(j in (1:(n-1))){
            Ksum &lt;- Ksum + (((epsilon[ii]/(sigma.sqs[ii]^0.5))-w[j])/h)
          }
  </code></pre>
  
  <p>The loop is supposed to calculate a vector of Ksum's, one for every x. I have been banging my head trying to find out what is wrong, but i have become blind for the solution.</p>
  
  <p>Any ideas?</p>
  
  <p>Cheers</p>