2014-05-03 22:27:34 +08:00
|
|
|
package pairwise
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math"
|
|
|
|
|
2015-10-24 22:44:24 -07:00
|
|
|
"github.com/gonum/matrix"
|
2018-03-23 23:39:55 +00:00
|
|
|
"gonum.org/v1/gonum/mat"
|
2014-05-03 22:27:34 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type Manhattan struct{}
|
|
|
|
|
|
|
|
func NewManhattan() *Manhattan {
|
|
|
|
return &Manhattan{}
|
|
|
|
}
|
|
|
|
|
2014-07-18 13:48:28 +03:00
|
|
|
// Distance computes the Manhattan distance, also known as L1 distance.
|
|
|
|
// == the sum of the absolute values of elements.
|
2018-03-23 23:39:55 +00:00
|
|
|
func (m *Manhattan) Distance(vectorX *mat.Dense, vectorY *mat.Dense) float64 {
|
2014-05-04 22:58:32 +02:00
|
|
|
r1, c1 := vectorX.Dims()
|
|
|
|
r2, c2 := vectorY.Dims()
|
|
|
|
if r1 != r2 || c1 != c2 {
|
2015-10-24 22:44:24 -07:00
|
|
|
panic(matrix.ErrShape)
|
2014-05-03 22:47:41 +08:00
|
|
|
}
|
2014-05-03 22:27:34 +08:00
|
|
|
|
|
|
|
result := .0
|
|
|
|
|
2014-05-04 22:58:32 +02:00
|
|
|
for i := 0; i < r1; i++ {
|
|
|
|
for j := 0; j < c1; j++ {
|
|
|
|
result += math.Abs(vectorX.At(i, j) - vectorY.At(i, j))
|
|
|
|
}
|
|
|
|
}
|
2014-05-05 08:32:38 +02:00
|
|
|
return result
|
2014-05-03 22:27:34 +08:00
|
|
|
}
|