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)