Question

I can create a large matrix of zeros and replace a rectangular region within the matrix with ones like so:

import numpy as np

z = np.zeros((400,400))
z[192:206,196:202] = 1

How would I replace a circular region in the matrix with ones? The circle's radius can be arbitrarily big.

Was it helpful?

Solution

Here is a method to do what you have asked, specifying the circle centre and radius:

import numpy as np
import matplotlib.pyplot as plt
z = np.zeros((400,400))

# specify circle parameters: centre ij and radius
ci,cj=232,145
cr=20

# Create index arrays to z
I,J=np.meshgrid(np.arange(z.shape[0]),np.arange(z.shape[1]))

# calculate distance of all points to centre
dist=np.sqrt((I-ci)**2+(J-cj)**2)

# Assign value of 1 to those points where dist<cr:
z[np.where(dist<cr)]=1

# show result in a simple plot
fig=plt.figure()
ax=fig.add_subplot(111)
ax.pcolormesh(z)
ax.set_aspect('equal')
plt.show()

I used ax.set_aspect('equal') to show that it is indeed a circular region. I leave other aspects, like checking that the circle falls entirely within the bounds of the domain, up to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top