Skip to content

Instantly share code, notes, and snippets.

@straussmaximilian
Created September 21, 2019 12:50
Show Gist options
  • Save straussmaximilian/ec224678ba4988ec34ee0878bdcfaff6 to your computer and use it in GitHub Desktop.
Save straussmaximilian/ec224678ba4988ec34ee0878bdcfaff6 to your computer and use it in GitHub Desktop.
import numpy as np
def random_array(size, dim=3):
"""
Generate a random array of size size and dimension dim
"""
return np.random.rand(int(size), dim)
def loop(array):
"""
Takes a numpy array and isolates all points that are within [0.2,0.4]
for the first column and between [0.4,0.6] for the second column by
looping through every point.
"""
filtered_list = []
for i in range(len(array)):
# Check if the point is within the rectangle
if ((array[i][0] >= 0.2)
and (array[i][1] >= 0.4)
and (array[i][0] <= 0.4)
and (array[i][1] <= 0.6)):
filtered_list.append(array[i])
return np.array(filtered_list)
# Generate a random array of size 1e5
array = random_array(1e5)
filtered_array = loop(array)
# Measure code execution with inline magic (Jupyter Notebook)
print('Loop:\t', end='')
%timeit loop(array)
# Plot the results
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(10, 10))
plt.title('Filtered points in rectangle')
plt.plot(array[:, 0], array[:, 1], 'k.')
plt.plot(filtered_array[:, 0], filtered_array[:, 1], 'r.')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment