1

我正在 R 中构建一个简单的蚁群优化代码,但是我在编译一个函数以使用“break”语句为每个蚂蚁获取最佳路线时遇到问题。在我的循环中总是出现一个错误,说“需要 TRUE/FALSE 的地方缺少值”。这是代码

rm(list = ls())

x = c(11.7057,17.4151,1.4992,14.9609,9.5711)
y = c(11.1929,10.7112,17.0964,12.2228,6.7928)
n = length(x)

m = 20
t = matrix(0.0001,ncol=n,nrow=n)
beta = 1
alpha = 5
miter = 100

d = matrix(c(rep(0,n*n)),ncol=n,byrow=FALSE)
for (i in 1:n){
  for (j in 1:n){
    d[i,j] = sqrt((x[i]-x[j])^2+(y[i]-y[j])^2)
  }
}
d

h = matrix(c(rep(0,n*n)),ncol=n,byrow=FALSE)
for (i in 1:n){
  for (j in 1:n){
    if (d[i,j]==0){
      h[i,j]=0
    }
    else{
      h[i,j]=1/d[i,j]
    }
  }
}
h

antour <- function(a1,a2,a3,a4,a5,a6,a7){
for (i in 1:m){
    mh = h
    for (j in 1:n-1){
      a = start_places[i,j]
      mh[,c(a)]=0
      temp = (t[c(a),]^alpha)*(mh[c(a),]^beta)
      q = sum(temp)
      p = (1/q)*temp
      r = runif(1)
      s = 0
      for (k in 1:n){
        s = s+p[k]
        start_places[i,j+1] = k
        if (r <= s){
          break
        }
        print(start_places)
      }
    }
  }
  new_places = start_places
}


for (i in 1:miter){
  start_places = matrix(c(rep(1,m)),ncol=1)
  tour = antour(a1=start_places,a2=m,a3=n,a4=h,a5=t,a6=alpha,a7=beta)
}

我期望在循环过程中,start_places[i,j+1]=k当r <= s的值时得到每只蚂蚁的最优路径,但实际输出是错误总是出现如下

output is Error in if (r <= s) { : missing value where TRUE/FALSE needed
4

0 回答 0