我试着运行教科书中给出的例子"使用R&#34建模和求解线性规划;可以找到教科书的链接here
我尝试复制第75页第3.8章中的确切代码,但似乎打印出不同的结果
Assignment01 <- function(c){
n <- dim(c)[1]
coef <- as.vector(t(c))
rhs <- rep(1,2*n)
Amatrix <- matrix(0, 2*n, n*n)
for(i in 1:n){
for(j in 1:n){
Amatrix[i, n*(i-1)+j] <- 1
}
}
for(i in 1:n){
for(j in 1:n){
Amatrix[n+i, n*(j-1)+i] <- 1
}
}
signs <- rep("==", 2*n)
var_type <- rep("B", 2*n)
library(Rglpk)
solution <- Rglpk_solve_LP(obj=coef, mat=Amatrix, dir=signs, types=var_type, rhs=rhs, max=TRUE)
return(solution)
}
Assignment02 <- function(c){
n <- dim(c)[1]
coef <- c(rep(0, n*n),1)
rhs <- c(rep(1, 2*n), rep(0,n))
Amatrix <- matrix(0, 3*n, n*n + 1)
for(i in 1:n){
for(j in 1:n){
Amatrix[i, n*(i-1)+j] <- 1
}
}
for(i in 1:n){
for(j in 1:n){
Amatrix[n+i, n*(j-1)+i] <- 1
}
}
for(i in 1:n){
for(j in 1:n){
Amatrix[2*n+1, n*(j-1)+i] <- c[j,i]
}
}
for(i in 1:n){
Amatrix[2*n+1, n*n + 1] <- -1
}
signs <- c(rep("==", 2*n),rep(">=",n))
var_type <- c(rep("B", n*n), "C")
library(Rglpk)
solutionPL <- Rglpk_solve_LP(obj=coef, mat=Amatrix, dir=signs, types=var_type, rhs=rhs, max=TRUE)
return (solutionPL)
}
set.seed(1)
c <- matrix(sample(10:100, 25),100,100)
solAss01 <- Assignment01(c)
m.01 <- matrix(solAss01$solution[1:25],5,5, byrow=TRUE)
solAss02 <- Assignment02(c)
m.02 <- matrix(solAss02$solution[1:25],5,5,byrow=TRUE)
print(m.01)
print(m.02)
并获得此输出
答案 0 :(得分:1)
此代码无法编译:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="36px" height="36px" viewBox="0 0 36 36" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs></defs>
<g id="States" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Buttons-&-States-(Documents-Steps)" transform="translate(-104.000000, -138.000000)">
<g id="Close-Button" transform="translate(104.000000, 138.000000)">
<g>
<circle id="circle" fill="#E9EEF2" cx="18" cy="18" r="18"></circle>
<polygon id="X" fill="#9FADB5" transform="translate(17.868000, 17.808000) rotate(-45.000000) translate(-17.868000, -17.808000) " points="16.968 23.616 18.768 23.616 18.768 18.672 23.736 18.672 23.736 16.944 18.768 16.944 18.768 12 16.968 12 16.968 16.944 12 16.944 12 18.672 16.968 18.672"></polygon>
</g>
</g>
</g>
</g>
我相信你会for(j in 1:){
与x(i,j)
混淆。 c(i,j)
值为零,每行和每列只有一个x
。
另请注意,1
c(i,j)
的每个j
具有相同的值:
> c[1:5,1:5]
[,1] [,2] [,3] [,4] [,5]
[1,] 34 34 34 34 34
[2,] 43 43 43 43 43
[3,] 60 60 60 60 60
[4,] 89 89 89 89 89
[5,] 27 27 27 27 27