So here is the problem:
Given 2D numpy arrays 'a' and 'b' of sizes n×m and k×m respectively and one natural number 'p'. You need to find the distance(Euclidean) of the rows of the matrices 'a' and 'b'. Fill the results in the k×n matrix. Calculate the distance with the following formula $$ D(x, y) = \left( \sum _{i=1} ^{m} \left| x_i - y_i \right|^p \right) ^{1/p} ; x,y \in R^m $$ (try to prove that this is a distance). Extra points for writing without a loop.
And here is my solution:
import numpy as np
def dist_mat(a, b, p):
result = []
print(result)
for vector in b:
matrix = a - vector
print(matrix)
result.append(list(((matrix ** p).sum(axis=1))**(1/p)))
return np.array(result)
a = np.array([[1, 1],
[0, 1],
[1, 3],
[4, 5]])
b = np.array([[1, 1],
[-1, 0]])
p = 2
print(dist_mat(a, b, p))
I'm not sure about using Python list
and then converting it into np.array
, is there a better way?
matrix = abs(a - vector)
according to the provided formula. Doesn't matter for an even valuep
, but does for odd values. Might be wrong though. \$\endgroup\$scipy.spatial.distance_matrix()
for testing. docs.scipy.org/doc/scipy/reference/generated/… \$\endgroup\$