r - matrix with row and column constraints -


i need solve n x n (n <12) matrix subject few constraints:

1.predetermined row , column sums satisfied.

2.each element in matrix having row number greater column number must 0 (so nonzero elements must in top right portion).

3.for given row, every element more 3 columns right first nonzero element must zero.

so, 4x4 matrix might (the row , column constraints larger in practice, around 1-3 million):

|3 2 1 0| = 6 |0 2 1 1| = 4 |0 0 2 1| = 3 |0 0 0 4| = 4  3 4 4 6 

i have been trying use solver approaches in excel , have tried r based optimization packages have been unsuccessful far.

any suggestions on how else might approach appreciated.

thanks!

test data:

x <- c(2,2,2,1,1,1,1) rowvals <- c(6,4,3,4) colvals <- c(3,4,4,6) 

function construct appropriate test matrix (3n-5) parameters:

makemat <- function(x,n) {     ## first , last element of diag constrained row/col sums     diagvals <- c(colvals[1],x[1:(n-2)],rowvals[n])     ## set off-diagonals 2,3     sup2vals <- x[(n-1):(2*n-3)]     sup3vals <- x[(2*n-2):(3*n-5)]     ## set matrix     m <- diag(diagvals)     m[row(m)==col(m)-1] <- sup2vals     m[row(m)==col(m)-2] <- sup3vals     m } 

objective function (sum of squares of row & column deviations):

objfun <- function(x,n) {     m <- makemat(x,n)     ## compute ssq deviation row/col constraints     sum((rowvals-rowsums(m))^2+(colvals-colsums(m))^2) } 

optimizing:

opt1 <- optim(fn=objfun,par=x,n=4) ## recovers original values, although takes lot of steps  opt2 <- optim(fn=objfun,par=rep(0,length(x)),n=4) makemat(opt2$par,n=4) ##      [,1]     [,2]      [,3]      [,4] ## [1,]    3 2.658991 0.3410682 0.0000000 ## [2,]    0 1.341934 1.1546649 1.5038747 ## [3,]    0 0.000000 2.5042858 0.4963472 ## [4,]    0 0.000000 0.0000000 4.0000000 ##   ## conjugate gradients might better opt3 <- optim(fn=objfun,par=rep(0,length(x)),n=4,               method="cg") 

it seems there multiple solutions problem, isn't surprising (since there 2n constraints on (n-2)+(n-1)+(n-2)= 3n-5 parameters).

you didn't whether need integer solutions or not -- if need more specialized tools ...


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -