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
radius = 20
halfwidth = width/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 - 
radius, j+halfwidth-radius]]=1]]]]

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:

Not very circular circle

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?


  • 1
    $\begingroup$ Try this: With[{radius = 20, width = 100}, Image@DiskMatrix[radius, width] ] $\endgroup$
    – flinty
    Commented Oct 29, 2020 at 20:18

1 Answer 1


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

array = ConstantArray[0, {height, width}];
array=ReplacePart[array, {i_, j_} /; (i - x0)^2 + (j - y0)^2 < r^2 :> 1];

enter image description here

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}];

enter image description here

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}];

enter image description here

  • 1
    $\begingroup$ The functional method worked beautifully. Thank you. $\endgroup$ Commented Oct 29, 2020 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.