This is my first time using the optim function in R, and I am having some trouble figuring out what I am doing wrong.
I want to find the maximum for the phi function. I am optimizing over the vector C.
Phi <- function(C, mu, sigma, xbar, P, alpha){
X <- xbar+ P%*%C
return(mu %*% X - alpha * t(X) %*% sigma %*% X)
}
mu, sigma, xbar, P, and alpha are predefined scalars, vectors, and matrices.
The gradient for the phi function is:
Gradient <- function(C, mu, sigma, xbar, P, alpha){
X <- xbar+P%*%C
n <- length(C)
grad <- rep(0,n)
for(j in 1:n){
grad[j] <- mu - 2*alpha*t(X) %*% sigma
}
return(grad)
}
I tried using the optim function as below:
results <- optim(par = start, fn = Phi, gr = Gradient, method = "CG")
"start" is a predefined vector with the same dimensions for C.
However, when I try running the optim function, I get the following error:
> results <- optim(par = start, fn = Phi, gr = Gradient, method = "CG")
Error in xbar + P %*% C : 'xbar' is missing
What am I doing wrong? I would appreciate any guidance! Thanks in advance.
Edit: I defined my start vector as such-
Start <- function(n){
vector <- rep(1/n, n)
return(vector)
}
start <- Start(length(mu)-1)
As correctly stated by @Maciej, you have additional parameters mu, sigma, xbar, P, alpha
, which are declared, but not supplied to an optim()
call.
To supply these parameters, an ellipsis ...
can be used, where you specify them in a form name=value
.
Here's a small example of how a function with parameters can be optimized:
f <- function(x, param) sum((x-param)^2)
optim(par=c(0,0,0), fn=f, param=1:3)
$par
[1] 1.000538 1.999985 2.999919
$value
[1] 2.966097e-07
$counts
function gradient
112 NA
$convergence
[1] 0
$message
NULL