Calculate distances and save into matrix