Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # In this task, I have a 10xN matrix. That symbolizes a vector of vectors. We have 10 vectors (row = vector with coordinates).
- # Each inner vector has N coordinates (we are in the N-d domain)
- from math import sqrt
- from random import randrange
- from timeit import default_timer as timer
- # Function 1 - Initialization of the vectors
- def initializeMatrix(numOfVectors, N, LIMITinclusive):
- if numOfVectors <= 0 or N <= 0 or numOfVectors != int(numOfVectors) or N != int(N):
- print("Error while using the function '" + initializeMatrix.__name__ + "'")
- else:
- matrix = list()
- for i in range(numOfVectors):
- vector = list()
- for j in range(N):
- vector.append(randrange(0, LIMITinclusive + 1))
- matrix.append(vector)
- return matrix
- # Function 2 - Find the distances of every vector with the other vectors
- def distance(v1, v2):
- if len(v1) != len(v2):
- print("Error while using the function '" + distance.__name__ + "'")
- else:
- N = len(v1)
- normSquared = 0
- for i in range(N):
- normSquared += (v1[i] - v2[i]) ** 2
- norm = sqrt(normSquared)
- return norm
- # Function 3 - Create a numOfVector x numOfVector matrix with all the distances
- def distances(matrix):
- N = len(matrix)
- distances = [[0 for _ in range(N)] for __ in range(N)]
- for i in range(N):
- for j in range(N):
- distances[i][j] = distance(matrix[i], matrix[j])
- # The variables "distances" is a NxN matrix <----> list in list
- return distances
- # Function 4 - Pretty Distances
- def prettyDistances(matrix):
- DISTANCES = distances(matrix)
- for i in range(len(DISTANCES)):
- print(DISTANCES[i])
- # Function 5 - Return a matrix, where the 1st element is the closest distance of the 1st spot with the other spots,
- # the 2nd element is the closest distance of the 2nd spot with the other spots
- def minimumDistances(matrix):
- N = len(matrix)
- DISTANCES = distances(matrix)
- mins = list()
- for i in range(N):
- # DISTANCES[i] = a vector with all the distances, containing the zero distance (0)
- # that has been calculated between an object and itself
- d = DISTANCES[i]
- d.remove(0)
- mins.append(min(d))
- return mins
- # MAIN FUNCTION
- start = timer()
- print("******** Matrix ********")
- numOfvectors = 100
- N = 40
- LIMIinclusive = 1000
- matrix = initializeMatrix(numOfvectors, N, LIMIinclusive)
- print(matrix)
- print()
- print("******** Distances ********")
- print(distances(matrix))
- print()
- prettyDistances(matrix)
- print()
- print("******** Minimum Distances for every spot ********")
- print(minimumDistances(matrix))
- end = timer()
- print()
- print("******** Execution time ********")
- elapsed = end - start
- elapsed = round(elapsed, 2)
- print("Execution time for", numOfvectors, "vectors in", N, "- D domain is:", elapsed, "seconds")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement