i am trying to run a simple optimization problem and i always get the 'non-conformable arguments' error. However the error occurs only within optim, so i am at the end of my understanding. Here is my code:
f <- function(W, x, y){
temp <- W %*% x
temp1 <- t(temp) %*% temp
temp2 <- t(temp) %*% y
temp3 <- t(y) %*% y
(temp1 - 2 * temp2 temp3)[1]
}
x <- matrix(c(1,2), ncol=1)
y <- matrix(c(5,3), ncol=1)
W <- matrix(c(1,2,3,4), ncol=2)
f(W,x=x,y=y)
> 53
so far so good. The function works just fine. However once i put the values into optim:
optim(par=W, fn=f, x=x, y=y)
i get:
> Error in W %*% x : non-conformable arguments
how can i fix this?
CodePudding user response:
If you add print(W)
at start of f
you would see that W
is used as vector (it seems that optim
converts par
to vector). You should transform W
to matrix with adequate dimensions at start of f
.