2024-heraklion-data/exercises/numpy_vectorize/numpy_vectorize_solution.ipynb
2024-08-27 15:27:53 +03:00

2.4 KiB

In [ ]:
%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np

Vectorize this code

In [ ]:
size = 101
center = size // 2
radius = 20

circle = np.zeros((size, size), dtype=float)
for i in range(size):
    for j in range(size):
        distance_from_center = np.sqrt((i - center)**2 + (j - center)**2)
        if distance_from_center <= radius:
            circle[i, j] = 1
In [ ]:
plt.imshow(circle)

Solution

In [ ]:
size = 101
center = size // 2
x = np.arange(size)
y = x.reshape((size, 1))
In [ ]:
distance_from_center = np.sqrt((x - center) ** 2 + (y - center) ** 2)
circle = distance_from_center <= radius
In [ ]:
plt.imshow(circle)
In [ ]: