# 为离散仓库位置问题构建成本矩阵的R代码。

``````# 一个计算欧氏距离的函数，基于两个数字向量作为输入。
euclidean_distance <- function(df1,df2){
sqrt((df1[,1]-df2[,1])**2+(df1[,2]-df2[,2])**2)
}

# 参数：df为仓库坐标，df为客户坐标。
cost_matrix <- function(warehouses,customers){
matrix <- as.data.frame(matrix(nrow=nrow(customers),ncol=nrow(warehouses)))
# 应用欧氏距离
for(i in 1:nrow(customers)){
df <- as.data.frame(matrix(nrow=nrow(warehouses),ncol=2))
df[,1] <- as.numeric(rep(customers[i,1],times=nrow(df)))
df[,2] <- as.numeric(rep(customers[i,2],times=nrow(df)))
matrix[i,] <- euclidean_distance(df,warehouses)
}
# 返回成本矩阵
matrix
}``````
`我在下面的代码片段中进行简单的测试，并在底部打印成本矩阵。`
``````# 按经度和纬度分列的候选仓库地点；
warehouse_df <- as.data.frame(matrix(nrow=3,ncol=2))
colnames(warehouse_df)<-c("lat","long")
warehouse_df\$lat <- runif(n=3,min=-90,max=90)
warehouse_df\$long <- runif(n=3,min=-180,max=180)
head(warehouse_df)``````
``````##         lat       long
## 1 -44.17554  102.08728
## 2 -58.51864 -160.25027
## 3 -56.54944  -11.30273``````
``````# 客户地点
customers_df <- as.data.frame(matrix(nrow=4,ncol=2))
colnames(customers_df)<-c("lat","long")
customers_df\$lat <- runif(n=4,min=-90,max=90)
customers_df\$long <- runif(n=4,min=-180,max=180)
head(customers_df)``````
``````##         lat      long
## 1 -15.70044  171.1968
## 2 -87.68773 -156.7455
## 3 -62.35740  117.7821
## 4 -85.57747 -102.7820``````
``````#测试成本矩阵函数
cost_matrix(warehouse_df,customers_df)``````
``````##          V1        V2       V3
## 1  74.74596 334.20139 187.0153
## 2 262.46471  29.37890 148.7387
## 3  24.01888 278.05884 129.2154
## 4 209.01088  63.51993  95.9744``````