Skip to content
DeepForgeby svx
All problems
MediumLinear Algebrala-172

Mahalanobis Distance (Diagonal Covariance)

Problem

Compute the Mahalanobis distance between x and y under a diagonal covariance with variances given per dimension:

d = sqrt(sum((x[i] - y[i])^2 / variances[i]))

Assume all variances are positive.

Hint

Scaling each axis by its standard deviation turns this into a Euclidean distance.

Test cases

case 1
in: [[1,2],[2,4],[1,1]]
expected: 2.23606797749979
case 2
in: [[1,2],[2,4],[1,4]]
expected: 1.4142135623730951
case 3
in: [[1,1],[1,1],[1,1]]
expected: 0
case 4
in: [[0,0],[3,4],[9,16]]
expected: 1.4142135623730951
Starter codePython
def mahalanobis_diagonal(x, y, variances):
    # Your code here
    pass

4 test cases · run your code against them in the editor