How to generate Cauchy Matrix from arrays in Numpy?

Learn how to generate Cauchy matrices from NumPy arrays using the np.subtract.outer() function for numerical computing applications.

Numpy cauchy matrix from arrays

Generating matrices

Initially, I generated two arrays, each with six elements. The first array ranges from 10 to 12, and the second from 4 to 8, utilizing the linspace function from NumPy.

Cauchy Matrix will be generated by below code:
cauchy_matrix = 1/np.subtract.outer(my_array, my_second_array)

import numpy as np

my_array = np.linspace(10, 12, 6)
my_second_array = np.linspace(4, 8, 6)

cauchy_matrix = 1/np.subtract.outer(my_array, my_second_array)

print(f"My first array: \n {my_array}")
print(f"My second array: \n {my_second_array}")

print(f"Cauchy Matrix generated based on above arrays: \n{cauchy_matrix}")

The resulting Cauchy matrix contains computed values using the reciprocal of element-wise differences between the two input arrays.

[[0.16666667 0.19230769 0.22727273 0.27777778 0.35714286 0.5       ]
 [0.15625    0.17857143 0.20833333 0.25       0.3125     0.41666667]
 [0.14705882 0.16666667 0.19230769 0.22727273 0.27777778 0.35714286]
 [0.13888889 0.15625    0.17857143 0.20833333 0.25       0.3125    ]
 [0.13157895 0.14705882 0.16666667 0.19230769 0.22727273 0.27777778]
 [0.125      0.13888889 0.15625    0.17857143 0.20833333 0.25      ]]

How to generate a Cauchy matrix from two arrays in NumPy?

In addition to generating a Cauchy matrix from a single array, you can also generate a Cauchy matrix from two arrays. To do this, you can use the subtract.outer function. The subtract.outer function takes two arrays as parameters and subtracts the elements of the first array from the corresponding elements of the second array. The result is a matrix of the differences between the elements of the two arrays.

See also  How to you find the cumulative sum in Python?

The Cauchy matrix can then be generated by dividing 1 by the matrix of differences. For example, the following code will generate a Cauchy matrix from two arrays with 6 elements:

import numpy as np

my_array = np.linspace(10, 12, 6)
my_second_array = np.linspace(4, 8, 6)

cauchy_matrix = 1 / np.subtract.outer(my_array, my_second_array)

print(cauchy_matrix)

This code will print the following output:

[[0.16666667 0.19230769 0.22727273 0.27777778 0.35714286 0.5       ]
 [0.15625    0.17857143 0.20833333 0.25       0.3125     0.41666667]
 [0.14705882 0.16666667 0.19230769 0.22727273 0.27777778 0.35714286]
 [0.13888889 0.15625    0.17857143 0.20833333 0.25       0.3125    ]
 [0.13157895 0.14705882 0.16666667 0.19230769 0.22727273 0.27777778]
 [0.125      0.13888889 0.15625    0.17857143 0.20833333 0.25      ]]

As demonstrated, the resulting Cauchy matrix exhibits symmetry and consists solely of positive elements.

See also  How to calculate square root in Numpy?