## If I start with a matrix of zeros, how can I easily create a circle of ones in that matrix?

Asked by Daniel Gray

### Daniel Gray (view profile)

on 27 Jun 2017
Latest activity Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 27 Jun 2017
Accepted Answer by Andrei Bobrov

### Andrei Bobrov (view profile)

I have a matrix of zeros, but would like a circle of ones in that matrix. Preferably I would like the circle to fill half the area of the matrix, but this is not a necessity.

Andrei Bobrov

on 27 Jun 2017
See here.

### Tags

Answer by Andrei Bobrov

### Andrei Bobrov (view profile)

on 27 Jun 2017
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 27 Jun 2017

Use function bwdist from Image Processing Toolbox:
N = 1001;
R = 400;
M = zeros(N);
ii = ceil(N/2);
M(ii,ii) = 1;
out = bwdist(M) <= R;
imagesc(out)
or without Image Processing Toolbox:
N = 1001;
R = floor(sqrt(N.^2/pi/2)); %"... circle to fill half the area of the matrix..."
ii = abs(floor((1:N) - N/2));
out = hypot(ii',ii) <= R; % MATLAB R2016b and later
out = bsxfun(@hypot,ii',ii) <= R; % MATLAB R2016a and earlier
imagesc(out)

Answer by Shane L

### Shane L (view profile)

on 27 Jun 2017

One way to do it (not necessarily the most efficient, but easy to understand):
Z = zeros(99); % create square matrix of zeroes
origin = [round((size(Z,2)-1)/2+1) round((size(Z,1)-1)/2+1)]; % "center" of the matrix
radius = round(sqrt(numel(Z)/(2*pi))); % radius for a circle that fills half the area of the matrix
[xx,yy] = meshgrid((1:size(Z,2))-origin(1),(1:size(Z,1))-origin(2)); % create x and y grid
Z(sqrt(xx.^2 + yy.^2) <= radius) = 1; % set points inside the radius equal to one
imshow(Z); % show the "image"