Cost matrix for warehouse location problem (in R)

Operations research provides a range of algorithms for determining exact optimal solutions to discrete warehouse location problems. However, these algorithms require a cost matrix, specifying the cost for supplying customer i from warehouse j, for each customer and each warehouse.

Below, I propose an algorithm for specifying this cost matrix such that one can apply these algorithms. The calculation is based on euclidean distances as a cost measure, i.e. assumes linearly scaled variable costs based on euclidean distances.

# a function for calculating euclidean distances, based on two numeric vectors as input
euclidean_distance <- function(df1,df2){

# parameters: df with warehouse coordinates, df with customers coordinates
cost_matrix <- function(warehouses,customers){
  matrix <-,ncol=nrow(warehouses)))
  # applying euclidean distances
  for(i in 1:nrow(customers)){
    df <-,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)
  # return cost matrix

I perform a simple test in the code snippet below, and print the cost matrix at the bottom.

# discrete candidate warehouse locations, by latitude and longitude
warehouse_df <-,ncol=2))
warehouse_df$lat <- runif(n=3,min=-90,max=90)
warehouse_df$long <- runif(n=3,min=-180,max=180)
##         lat       long
## 1 -44.17554  102.08728
## 2 -58.51864 -160.25027
## 3 -56.54944  -11.30273
# customer locations
customers_df <-,ncol=2))
customers_df$lat <- runif(n=4,min=-90,max=90)
customers_df$long <- runif(n=4,min=-180,max=180)
##         lat      long
## 1 -15.70044  171.1968
## 2 -87.68773 -156.7455
## 3 -62.35740  117.7821
## 4 -85.57747 -102.7820
# test cost matrix function
##          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

I some of my other posts you can find examples on how to locate warehouses at center of mass (center of mass calculation in R) and how to assign customers to the nearest warehouse (customer assignment problem). I also provided an example on how to cluster customers into groups, based on their spatial proximity (spatial proximity customer grouping in R).

Lastly, I also have written a post on how to locate multiple warehouses at each their center of mass (locating multiple warehouses at center of mass).

You May Also Like

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.