Reputation: 97
I was trying run the example given in the textbook named "Modeling and Solving Linear Programming with R" the link to the textbook can be found here
I tried copying the exact code from the chapter 3.8 on page 75 but it seems that it prints out different result
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)
and got this output
Upvotes: 0
Views: 66
Reputation: 16752
This code does not compile:
for(j in 1:){
I believe you are confusing x(i,j)
with c(i,j)
. The x
values are zeros and ones with only one 1
in each row and column.
Also notice your c(i,j)
have the same value for each 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
Upvotes: 1