r - Minimize distance between matrices subject to row and column margin constraints -
i solve matrix possessing predetermined row , column totals closely resembles second predetermined matrix possessing same properties (but possibly different row/column totals).
so, both matrices must satisfy following: elements of must in range [0,1].
any element column number less row number must 0 in solution.
any element column number greater row number + 2 must 0.
so starting this:
0.07 0.17 0.47 0.29 0.07 0.1 0.14 0 0.31 0 0.07 0.18 0.07 0.32 0 0 0.15 0.04 0.19 0 0 0 0.18 0.18
i minimize ‘distance’ this:
0.10 0.21 0.37 0.32 0.10 0.11 0.12 0 0.33 0 0.10 0.13 0.10 0.33 0 0 0.12 0.09 0.21 0 0 0 0.13 0.13
such original row , column totals first matrix preserved. defining distance here sum of squared differences between ith, jth entries in each matrix, if issue reason ok using other measure.
so far have been trying using solnp in rsolnp package this:
rowvals<-c(.31,.32,.19,.18) colvals<-c(.07,.17,.47,.29) in<-c(.07,.15,.1,.18,.04,.14,.07) tar<-c(.1,.11,.12,0,0,.1,.13,.1,0,0,.12,.09,0,0,0,.13) tar<-matrix(tar,byrow=t,nrow=4) 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,4,5,6 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 fn<-function(inpt, targt, n, ...){ x<-makemat(inpt, n=n) y<-targt z<-sum((x-y)^2) z } ##equality constraint function eq<-function(x,...){c(rowsums(makemat(x,length(rowvals))),colsums(makemat(x,length(colvals))))} ##row/column constraints eqb<-c(rowvals, colvals) opt1<-solnp(pars = in, fun = fn, eqfun = eq, eqb = eqb, lb = rep(0,7), targt = tar, n=4)
however, when try solve getting error:
solnp-->redundant constraints found. poor solnp-->intermediate results may result.suggest solnp-->remove redundant constraints , re-optimize iter: 1 fn: 0.0116 pars: 0.07000 0.15000 0.10000 0.18000 0.04000 0.14000 0.07000 solnp--> solution not reliable....problem inverting hessian.
i have encountered this:
error in solve.default(a %*% t(a), constraint, tol = 2.220446e-16) : lapack routine dgesv: system singular: u[4,4] = 0
i hope explaining problem enough; suggestions on how might approach appreciated.
thanks.
thanks!
it looks using equality constraint function works:
##equality constraint function eq<-function(x,...){c(rowsums(makemat(x,length(rowvals)))[-c(4,3)],colsums(makemat(x,length(colvals)))[-1])} ##row/column constraints eqb<-c(rowvals[-c(4,3)], colvals[-1])
Comments
Post a Comment