0
votes

I need minimize a funtion based in Hsieh Model, using R language. The main objective is to minimize a distance function that depends on a set of other functions.

obj = function(x1){
  s = sf()
  h_til = h_tilf()
  w_til = w_tilf(x1)
  w_r = w_rf()
  p_ir = p_irf()
  #H_tr = H_trf(x1)
  W = Wf(x1)      
  f1 = matrix(0, i, r)
  f2 = matrix(0, i, r)    

  for (c in 1:i){
    for (j in 1:r){
      f1[c, j] = ( (W[c, j] - W_t[c, j]) / W_t[c, j] ) ** 2
      f2[c, j] = ( (p_ir[c, j] - p_t[c, j])  /  p_t[c, j] ) ** 2
}
}
    d1 = sum(f1)
    d2 = sum(f2)
    D = d1 + d2    
    return(D)  
}

Therefore, my algorithm must find three parameters (w, tau_w, tau_h) that minimize this distance function. These three parameters are arrays with i rows and r columns. Given by:

w = runif(i*r, 0, 1)
tau_w =  runif(i*r, -1, 1)
tau_h = runif(i*r, -1, 1)

x1 = array( c(tau_w, tau_h, w), dim = c(i, r, 3))

I trying solve this using optimx and Rsolnp libraries.


res = optim(x1,      #starting values 
            obj)   #function to optimise

But i get this error:

Error in x1[c, j, 1] : incorrect number of dimensions

This minimization is usually done using the Nelder-Mead algorithm. I'm beginner in optimization and apreciate any help. My complete code is here.

1

1 Answers

0
votes

The dimensions of the array x1 are lost when you do optim(x1, obj). So the error you get is returned by w_tilf(x1) because it involves x1[c,j,1].

Reconstruct the array at the beginning of the obj function:

obj = function(x1){
  x1 = array(x1, dim = c(i, r, 3))
  s = sf()
  ......
} 

Then opt <- optim(x1, obj) should work now. It will return the solution in the opt$par field as a vector, you will have to do array(opt$par, dim = c(i, r, 3)) to get an array.