Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optim function in R for D-optimality

I have made a function which returns the determinent of (X'X)^-1. I need to use the optim function on the function I created to give me the best values for the X matrix. I am having issues with getting optim to work, but my function is working fine.

fr <- function(x,nc,nr) {
Xd <- matrix(c(rep(1,nr),x),nrow=nr,ncol=nc) #### Design matrix
det(solve((t(Xd)%*%Xd))) #### det(FIM)
}

I have tried x as both a vector and as a matrix;

x <-
matrix(c(0.1,0.2,0.3,0.2,0.1,0,0.1,0.2,0.1,0.2,0.1,0.2,0.1,0.2,0.1,0.2,0.1,0.2,0.1,0.2),nro    w = 10, ncol = 2)
x <- c(0.1,0.2,0.3,0.2,0.1,0,0.1,0.2,0.1,0.2,0.1,0.2,0.1,0.2,0.1,0.2,0.1,0.2,0.1,0.2)

These are a few variations I have attemped with optim, all without success;

optim((x, 3, 10), fr)
optim(fn = fr, par = c(x=x, nc=3, nr=10))
optim(c(x,3,10), fr)

I get different errors, sometimes for having a comma after the x in optim, sometimes an error in .Internal about nrow missing.

like image 855
user2265910 Avatar asked Feb 19 '26 10:02

user2265910


1 Answers

You can pass the arguments for fr to optim:

opt <- optim(fn=fr, x, nc=3, nr=10)

this gives

> opt$par
         [,1]       [,2]
 [1,]  0.06933853 -1.0888672
 [2,]  0.07796119  1.8288789
 [3,]  2.09366322 -1.3050871
 [4,]  1.40676030  3.3006266
 [5,]  1.04102733 -1.1048119
 [6,] -5.84413537  1.6741804
 [7,] -4.75578972 -0.6484606
 [8,]  1.23037198  2.4842715
 [9,]  0.10477158  1.4135113
 [10,]  2.14145939 -1.4333241

To compare the function value of fr before and after optimization:

> fr(x,3,10)
[1] 62.5
> fr(opt$par, 3, 10)
[1] 4.963814e-05

Does this help?

You might want to check ?optim in case you want to set upper and lower bounds.

like image 161
user1981275 Avatar answered Feb 21 '26 15:02

user1981275



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!