'optim in R when the function to minimize depends implicitely on the parameters to adjust

I am trying to use the optim function in R to match theoretical data with experimental data. Basically, I have a function f which computes an output (say a matrix), depending on some parameters defined outside that function. For example, simplifying for clarity:

a=0.2
b=-5
c=9
f=function(dx,Xmax){
Nx=round(Xmax/dx) #Nb of columns
out=matrix(0,2,Nx) #Matrix initialization
for (i in 1:Nx){
  out[1,i]=(a^2*dx*i)/b #random example
  out[2,i]=(c*(dx*i)^2-b)/a #random example
 }
return(out)
}

result=f(0.1,10)

(The actual function f calls lots of functions outside, which use the parameters say a,b,c).

I have some experimental datas for some values of x, say (random again)

expr=data.frame(x=c(0,2,5,7),y=c(1,8,14,23))

I would like to use optim to adjust parameters a,b,c such that the function

WLS=function(theo,expr){
 #theo is extracted from the output of f
 out=sum((theo-y)/theo)^2) #weighted least squares
}

is minimized, where theo is given by function f for x related to expr (as the experimental data are for some values on x only)

The issue here is, from all the examples of optim I saw, the function to minimize (here WLS) must contain the parameters to vary as an argument. Is my only option is to insert a,b,c into the arguments of f (so we would have f=function(dt,Xmax,a,b,c)), then having something like for WLS

WLS=function(expr,param){
 theo=f(dt,Xmax,param[1],param[2],param[3])
 #then extract the values of theo for only the x I am interested in (not written here) and plugged 
  #into theo again
 out=sum((theo-y)/theo)^2) #weighted least squares
}

Or are there better ways to deal with that problem?

Thanks in adavance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source