Skip to content Skip to sidebar Skip to footer

Python: How To Create A Submatrix Discretizing A Circle?

In a 2D square grid (matrix) full of zeros, I need to create a submatrix full of ones, with the shape of this submatrix being as close as possible to a circle. I know a circle cann

Solution 1:

This function fills in a circle of 1s that looks pretty good.

def fill_cell(cell, corner, rad):
    m, n = cell.shape
    ctr = corner[0]+m/2, corner[1]+n/2
    x = np.arange(m) - ctr[0]
    y = np.arange(n) - ctr[1]
    X,Y = np.meshgrid(x, y, order='ij')  # could try order='xy'
    Z = ((X**2 + Y**2)<= rad**2).astype(cell.dtype)
    return Z
empty_lattice[:] = fill_cell(empty_lattice, (x,y),side/2)

Position in empty_lattice is not right - because of a difference in how you are defining the x,y coordinates and my assumptions, but I think you can sort that out.

Radius looks good, though it might be off by an integer.

To fill in multiple circles, you could iterate over the x,y values, and assign lattice values for a slice (view)

xyslice = slice(x,15), slice(y,15)
empty_lattice[xyslice] = fill_cell(empty_lattice[xyslice],...)

For overlapping circles I'd look into some sort of logical assignment

empty_lattice[xyslice] |= fill_cell(...)

Post a Comment for "Python: How To Create A Submatrix Discretizing A Circle?"