w3resource

NumPy: Compute the covariance matrix of two given arrays


8. Covariance Matrix of Two Arrays

Write a NumPy program to compute the covariance matrix of two given arrays.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array 'x' containing elements [0, 1, 2]
x = np.array([0, 1, 2])

# Creating an array 'y' containing elements [2, 1, 0]
y = np.array([2, 1, 0])

# Displaying the original array 'x'
print("\nOriginal array1:")
print(x)

# Displaying the original array 'y'
print("\nOriginal array1:")
print(y)

# Calculating the covariance matrix of arrays 'x' and 'y' using np.cov()
print("\nCovariance matrix of the said arrays:\n", np.cov(x, y)) 

Sample Output:

Original array1:
[0 1 2]

Original array1:
[2 1 0]

Covariance matrix of the said arrays:
 [[ 1. -1.]
 [-1.  1.]]

Explanation:

In the above exercise –

x = np.array([0, 1, 2]): This code creates a NumPy array x containing the values 0, 1, and 2.

y = np.array([2, 1, 0]): This code creates a NumPy array y containing the values 2, 1, and 0. print(np.cov(x, y)): This code calculates the covariance matrix of the arrays x and y using the np.cov() function, and then prints it to the console.


For more Practice: Solve these Related Problems:

  • Write a function that calculates the covariance matrix of two 1D arrays using np.cov and ensures the matrix is symmetric.
  • Create a program that computes the covariance of two 2D arrays after flattening them into 1D arrays.
  • Implement a solution that normalizes two arrays before computing their covariance and compares the output with np.cov.
  • Develop a method that computes covariance manually using the formula E[XY] - E[X]E[Y] and validates it against np.cov.

Go to:


Previous: Write a NumPy program to compute the mean, standard deviation, and variance of a given array along the second axis.
Next: Write a NumPy program to compute cross-correlation of two given arrays.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.