# How to make a discrete circle in a 2d array?

I'm trying to make a filled-in circle in a 2d matrix. Any value less than r is 1, and any value outside of r is zero. I'm looking for something that looks more circular as the array size grows. The circle should be centered in the array

I'm starting out with an array full of zeros, and trying to use a loop to assign values of 1, but I'm not getting anything that looks remotely like a circle.

Here's what I've tried:

width = 100
height = 100
halfwidth = width/2
halfheight=height/2

array = ConstantArray[0, {height, width}]
For[i=0, i<width, i++; For j=0, j<height, j++; If[i*i +j*j < radius*radius, array[[i + halfheight -


The last line SHOULD iterate over the entire 2d array and then checks if that index falls within the circle. If True, it assigns a value of 1, else it does nothing. Obviously, it's not doing that. This is what it produces: It looks like it might be creating a single quadrant of the circle, but if so its in the wrong place.

So, how do I center this, and make a complete circle?

Thanks!

• Try this: With[{radius = 20, width = 100}, Image@DiskMatrix[radius, width] ] Oct 29, 2020 at 20:18

If you really want to replace parts in an array, here's how I'd do it.

array = ConstantArray[0, {height, width}];
{x0,y0}={20,40};
r=5;
array=ReplacePart[array, {i_, j_} /; (i - x0)^2 + (j - y0)^2 < r^2 :> 1];
ArrayPlot[array] Otherwise I'd just go ahead and generate the array how I want it, using a function defined to decide if a given coordinate belongs in the circle.:

inCircle[{i_, j_}, r_, {x_, y_}] :=
If[(i - x)^2 + (j - y)^2 < r^2, 1, 0];

array=Table[inCircle[{i, j}, 5, {3, 2}], {i, -10, 10, 1}, {j, -10, 10, 1}];
ArrayPlot@array One benefit of this method is you can change the resolution pretty easily.

array=Table[inCircle[{i, j}, 5, {3, 2}], {i, -10, 10, 0.1}, {j, -10, 10, 0.1}];
ArrayPlot@array • The functional method worked beautifully. Thank you. Oct 29, 2020 at 21:14