The Cauchy matrix is a square matrix in which the elements of each row and column are defined by the formula 1/(xi  yj)
, where xi
and yj
are the ith
and jth
elements of two input arrays. NumPy provides efficient ways to construct the Cauchy matrix
using two input arrays. In this guide, we will walk through the steps to construct the Cauchy matrix
given two arrays, X
and Y
.
1. Using "broadcasting":
NumPy enables performing operations on arrays of different sizes or dimensions using a technique known as broadcasting
, which adjusts the arrays by adding dimensions or replicating elements as required.
In the above example, We use newaxis()
function to add a new axis to the array X
to make it a column vector, and then subtract the array Y
from it. This performs the elementwise subtraction of the array Y
from each element of the X
array. We then take the reciprocal of the result to obtain the Cauchy matrix
.
2. Using "subtract.outer()" and "divide()" functions:

np.subtract.outer()
computes the outer product of two arrays by performing elementwise subtraction between every element of the first array and every element of the second array. 
np.divide()
performs elementwise division of the first array by the second array.
The code defines two NumPy arrays, X and Y, with values [1, 2, 3] and [4, 5, 6], respectively. It then computes the Cauchy matrix using the np.subtract.outer()
and np.divide()
functions.
3. apply_along_axis() and a lambda functions:

The
apply_along_axis()
function in NumPy allows you to apply a specified function to a specific axis of a NumPy array. 
A
lambda
function in Python is a small anonymous function that can be defined in a single line of code. 
Lambda functions are useful for creating quick, throwaway functions that are only needed for a short period of time.
We use np.apply_along_axis()
to apply the kernel(lamba) function elementwise to the Y
array along its 0th
axis, and to the X
array with a new axis added using np.newaxis
. This computes the elementwise kernel function with each element of X
and each element of Y
, resulting matrix is the Cauchy matrix
.