On 09-02-2013, at 21:08, Axel Urbiz <axel.ur...@gmail.com> wrote: > Dear List, > > I'm new in R. I'm trying to solve a simple constrained optimization > problem. > > Essentially, let's say I have a matrix as in the object 'mm' inside the > function below. My objective function should have a matrix of parameters, > one parameter for each element 'mm' (4 in this case). The problem is to > select the value of the parameters to maximize the function 'ff' s.t. (1) > each parameter being either 0 or 1, and (2) the sum of each row in the > parameter matrix should equal 1. > > I'm using the function constrOptim as shown below, but obviously I'm not > doing things right. Any help is much appreciated. > > ff <- function (x) { > > mm <- matrix(c(10, 25, 5, 10), 2, 2) > matx <- matrix(NA, 2, 2) > > for (i in 1:nrow(x)) { > for (j in 1:ncol(x)) { > > matx[i, j] <- x[i, j] > } > > } > > -sum(apply(mm ^ matx, 1, prod)) > > } > > constrOptim(theta = c(0, 0, 0, 0), f = ff, ui=rbind(c(1, 1), > c(1, 1)), > ci=c(1, 1))
1. your parameter vector has length(4) 2. the ui matrix is 2x2 so ui %*% theta can't be done 3. ui should be something like rbind(c(1,1,0,0),c(0,0,1,1)) 4. you haven't specified the gradient function (grad); should be a function or NULL 5. in your function ff on entry x is a vector. It can be simplified to ff <- function (x) { mm <- matrix(c(10, 25, 5, 10), 2, 2) matx <- matrix(x,2,2) -sum(apply(mm ^ matx, 1, prod)) } then constrOptim(theta = c(1, 1, 1, 1), f = ff, grad=NULL, ui=rbind(c(1, 1,0,0),c(0,0,1, 1)),ci=c(1, 1)) gives: $par [1] -63.16203 120.71655 -135.39084 139.50023 $value [1] -1.797693e+308 $counts function gradient 501 NA $convergence [1] 0 $message NULL $outer.iterations [1] 2 $barrier.value [1] 0 which is probably not at all what you are looking for. Look in the CRAN Task View for Optimization for possible options for your optimization problem. Berend ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.