Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 具有行和列约束的矩阵_R_Excel_Vba_Optimization_Linear Algebra - Fatal编程技术网

R 具有行和列约束的矩阵

R 具有行和列约束的矩阵,r,excel,vba,optimization,linear-algebra,R,Excel,Vba,Optimization,Linear Algebra,我需要求解一个n x n(n通常测试数据: x <- c(2,2,2,1,1,1,1) rowVals <- c(6,4,3,4) colVals <- c(3,4,4,6) x感谢您的帮助,我不需要整数,只需要非负值。不过,似乎L-BFGS-B方法可以很好地满足这一要求。 x <- c(2,2,2,1,1,1,1) rowVals <- c(6,4,3,4) colVals <- c(3,4,4,6) makeMat <- function(x,n

我需要求解一个n x n(n通常测试数据:

x <- c(2,2,2,1,1,1,1)
rowVals <- c(6,4,3,4)
colVals <- c(3,4,4,6)

x感谢您的帮助,我不需要整数,只需要非负值。不过,似乎L-BFGS-B方法可以很好地满足这一要求。
x <- c(2,2,2,1,1,1,1)
rowVals <- c(6,4,3,4)
colVals <- c(3,4,4,6)
makeMat <- function(x,n) {
    ## first and last element of diag are constrained by row/col sums
    diagVals <- c(colVals[1],x[1:(n-2)],rowVals[n])
    ## set up off-diagonals 2,3
    sup2Vals <- x[(n-1):(2*n-3)]
    sup3Vals <- x[(2*n-2):(3*n-5)]
    ## set up matrix
    m <- diag(diagVals)
    m[row(m)==col(m)-1] <- sup2Vals
    m[row(m)==col(m)-2] <- sup3Vals
    m
}
objFun <- function(x,n) {
    m <- makeMat(x,n)
    ## compute SSQ deviation from row/col constraints
    sum((rowVals-rowSums(m))^2+(colVals-colSums(m))^2)
}
opt1 <- optim(fn=objFun,par=x,n=4)
## recovers original values, although it takes a 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 be better
opt3 <- optim(fn=objFun,par=rep(0,length(x)),n=4,
              method="CG")