Skip to content
DeepForgeby svx
All problems
MediumStatisticsst-028

Correlation Matrix 2x2

Problem

Return the 2x2 Pearson correlation matrix of x and y as [[1, r], [r, 1]]. Return [[0.0, 0.0], [0.0, 0.0]] when x is empty or the lengths differ, and use r = 0.0 when either variable has zero variance.

Hint

Fill the diagonal with 1.0 and place r in both off-diagonal cells.

Test cases

case 1
in: [[1,2,3,4],[2,4,6,8]]
expected: [[1,1],[1,1]]
case 2
in: [[1,2,3],[3,2,1]]
expected: [[1,-1],[-1,1]]
case 3
in: [[1,2,3,4,5],[2,4,1,3,5]]
expected: [[1,0.5],[0.5,1]]
case 4
in: [[5,5,5],[1,2,3]]
expected: [[1,0],[0,1]]
case 5
in: [[1,2,3,4],[1,3,2,5]]
expected: [[1,0.8315218406202999],[0.8315218406202999,1]]
Starter codePython
def correlation_matrix(x, y):
    # Your code here
    pass

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