Athii
Athii

Reputation: 130

Optimizing 2 sets of variable length vectors

I did searched the questions here before posting and I found only one question in this regard but it doesn't apply to my case.

I have uploaded the data for PRD, INJ, tao and lambda with the links below, which shall be used to reproduce the code:

PRD

INJ

lambda

tao

the code:

PRD=read.csv(file="PRD.csv")
INJ=read.csv(file="INJ.csv")
PRD=do.call(cbind, PRD)
INJ=do.call(cbind, INJ)
tao=do.call(cbind, read.csv(file="tao.csv",header=FALSE))
lambda=do.call(cbind, read.csv(file="lambda.csv",header=FALSE))
fn1 <- function (tao,lambda) {
#perparing i.dash  
  i.dash=matrix(ncol=ncol(INJ), nrow=(nrow(INJ)))
  for (i in 1:ncol(INJ)){
     for (j in 1:nrow (INJ)){
      temp=0
      for (k in 1:j){
        temp=(1/tao[i])*exp((k-j)/tao[i])*INJ[k,i]+temp
      }
      
      i.dash[j,i]=temp
     }
  
  #preparing lambdaXi.dash
  
  lambda.i=matrix(ncol=ncol(INJ),nrow=nrow(INJ))
 for (i in 1: ncol(INJ)){
   lambda.i[,i]=lambda[i+1]*i.dash[,i]
 }
  
 #calc. q. hat (I need to add the pp term)
 q.hat=matrix(nrow=nrow(INJ),1 )
  for (i in 1:nrow(INJ)){
    q.hat[i,1]=sum(lambda.i[i,1:ncol(INJ)])
  target= sum((PRD[,1]-q.hat[,1])^2)
   }
  }
}

what I am trying to do is to minimize the value target by optimizing lambda and tao which the starting values will be the same as the ones uploaded above. I've used optim to do so but I still receive the error cannot coerce type 'closure' to vector of type double

I've used many variations of optim and still recieve the same error.

the last syntax I've used was optim(fn1, tao=tao, lambda=lambda, hessian=T)

Thanks

Upvotes: 0

Views: 865

Answers (1)

seancarmody
seancarmody

Reputation: 6290

The calling form of optim is

optim(par, fn, gr = NULL, ...,
      method = c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN",
             "Brent"),
      lower = -Inf, upper = Inf,
      control = list(), hessian = FALSE)

So, you need to pass the parameters first, not the function. Note that "closure" is another term for "function", which explains the error message: you have passed a function as the first argument, when optim expected initial parameter values.

Note also, that optim only optimises over the first argument of the function fn, so you will need to redesign your function fn1 so it only takes a single function. For example, it could be a single vector where of the form c(n, t1, t2,...,tn, l1, l2, l3, ... lm) where ti are the components of tao and li components of lambda and n tells you how many components tao has.

Upvotes: 1

Related Questions