Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.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_Algorithm - Fatal编程技术网

R 分配算法变量

R 分配算法变量,r,algorithm,R,Algorithm,我在R中有一个方阵,包含城市之间的距离: set.seed(3) x <- matrix(sample(1:15, 16, replace = TRUE), nrow = 4) x # [,1] [,2] [,3] [,4] #[1,] 3 10 9 9 #[2,] 13 10 10 9 #[3,] 6 2 8 14 #[4,] 5 5 8 13 然而,在这种特殊情况下,我希望尽量减少距离的扩展。

我在R中有一个方阵,包含城市之间的距离:

set.seed(3)
x <- matrix(sample(1:15, 16, replace = TRUE), nrow = 4)
x
#     [,1] [,2] [,3] [,4]
#[1,]    3   10    9    9
#[2,]   13   10   10    9
#[3,]    6    2    8   14
#[4,]    5    5    8   13
然而,在这种特殊情况下,我希望尽量减少距离的扩展。 我已经搜索了很长一段时间,我发现了以下内容(以及类似的内容):

所以我们的目标是最小化最大和最小分配距离之间的差异,这正是我想要的。匈牙利算法的赋值给出了最大距离和最小距离之间的以下差异:

distances <- x[cbind(1:4, y)]
max(distances) - min(distances)
#[1] 7
距离2,2=>4,3=>1,4=>3 yNew
distances <- x[cbind(1:4, y)]
max(distances) - min(distances)
#[1] 7
#Optimal assignment to minimize the new objective:
#1 => 2, 2 => 4, 3 => 1, 4 => 3
yNew <- c(2, 4, 1, 3)
distancesNew <- x[cbind(1:4, yNew)]
max(distancesNew) - min(distancesNew)
#[1] 4