plot a solid circle using nested loops in matlab

Here is an example code to plot a solid circle using nested loops in MATLAB:

main.m
% Define radius of circle
radius = 5;

% Define center of circle
center = [0 0];

% Define step size for x and y coordinates
step_size = 0.1;

% Initialize array for x and y coordinates
x = [];
y = [];

% Nested loops to generate x and y coordinates for circle
for i = -radius:step_size:radius
    for j = -radius:step_size:radius
        if i^2 + j^2 <= radius^2
            x = [x, i+center(1)];
            y = [y, j+center(2)];
        end
    end
end

% Plot circle
plot(x, y, 'b.', 'MarkerSize', 10)
axis equal
517 chars
27 lines

In this code, we first define the radius and center of the circle. We also define the step size for the x and y coordinates, which determines the resolution of the circle (i.e., a smaller step size will result in more points and a smoother circle).

We then initialize empty arrays for the x and y coordinates. The nested loops iterate over all (i,j) pairs within a square with sides of 2*radius, and for each point within that square, we compute the distance from the point to the center of the circle. If the distance is less than or equal to the radius of the circle, we add the coordinates to the x and y arrays.

Finally, we plot the circle using the plot function, specifying that we want to use blue dots ('b.') to represent the points in the circle, with a marker size of 10. We also use axis equal to make sure that the x and y axes have the same scale.

related categories

gistlibby LogSnag