import numpy from numpy.linalg import norm A = numpy.array([[1, 2], [3, 4]]) B = numpy.array([[5, 6], [7, 8]]) d = norm((A-B), ord="fro") print("Matrix A: \n", A) print("Matrix B: \n", B) print("The Euclidean distance of the matrices A and B: ", d)
Here, A and B are two matrices. We are using the norm() function from numpy.linalg to calculate the Euclidean distance between these two matrices.
Here, we are first subtracting the matrix B from the matrix A. As a result, each element of the resultant matrix will be equal to (Ai,j – Bi,j), where Ai,j and Bi,j are the elements in the ith row and jth column of A and B, respectively. Now, we are calculating the Frobenius norm of the resultant matrix (A – B) (What is the Frobenius norm of a matrix?)
We know that he Frobenius norm of an mxn matrix A is defined as:
Here, Ai,j is the element in the ith row and jth column of the matrix A. In other words, if we take all the elements of the matrix, square them and sum them up and then, take the square root of the result, we will get the Frobenius norm of the matrix.
So, the Frobenius norm of the matrix (A-B) will be:
And that is the Euclidean distance between the matrices A and B.
The output of the mentioned program will be:
Matrix A: [[1 2] [3 4]] Matrix B: [[5 6] [7 8]] The Euclidean distance of the matrices A and B: 8.0






0 Comments