calculate cost matrix