+1 (315) 557-6473 

Python Program to Implement Numpy Arrays Assignment Solution.


Instructions

Objective
Write a python assignment to implement numpy arrays.

Requirements and Specifications

program to implement numpy arrays in python

Source Code

import numpy as np

def closest_point(A1, A2):

# Convert arrays to float64

A1 = A1.astype('float64')

A2 = A2.astype('float64')

# First, check that the number of columns in both arrays is the same

if A1.shape[1] != A2.shape[1]:

raise ValueError("Arrays must have the same number of columns")

# Compute the pair-wise difference between each row from A1 and A2

# Check if the matrices has same number of rows

if A1.shape[0] != A2.shape[0]:

diff = A1[np.newaxis,:,:]-A2[:,np.newaxis,:]

else:

diff = A1-A2

# Now compute the distance. The distance is calculated using the Euclidean Distance formula

dist = np.sqrt(np.sum(diff**2,axis=-1))

# Now, get the location of the minimum distance

loc = np.where(dist == dist.min())

if A1.shape[0] != A2.shape[0]:

pos = loc[1][0]

else:

pos = loc[0][0]

# The location contains two values: row and column. The row index

# is the point in A1 and the column index is the index in A2

return pos

# Test

if __name__ == '__main__':

# Generate two arrays of random numbers

#A1 = np.random.rand(150,2)

#A2 = np.random.rand(500,2)

A1 = np.array([[0,0],[1,1],[0,1],[1,0]])

A2 = np.array([[2,2],[2,3],[3,2],[3,3], [0.25,2]])

B1 = np.arange(10**6).reshape(10**4, 10**2)

B2 = np.array([0] * 10**6).reshape((10**4, 10**2))

# Compute

pos = closest_point(B1,B2)

print(pos)