plot a circle using nested loops in matlab

You can use nested loops to plot a circle in MATLAB. One way to do this is by evaluating the equation of a circle at discrete points along its circumference, and then plotting those points. The equation of a circle is:

main.m
(x - xc)^2 + (y - yc)^2 = r^2
30 chars
2 lines

where (xc, yc) are the coordinates of the circle's center, and r is its radius. To plot a circle with resolution n, you can sample angles from 0 to 2pi, and compute the corresponding x and y coordinates using the above equation:

main.m
for i = 1:n
    angle = i/n * 2*pi;
    x(i) = xc + r * cos(angle);
    y(i) = yc + r * sin(angle);
end
104 chars
6 lines

Then you can plot the points using the "plot" command:

main.m
plot(x, y);
12 chars
2 lines

Here's the complete code:

main.m
xc = 0;  % x-coordinate of center
yc = 0;  % y-coordinate of center
r = 1;   % radius
n = 100; % resolution

for i = 1:n
    angle = i/n * 2*pi;
    x(i) = xc + r * cos(angle);
    y(i) = yc + r * sin(angle);
end

plot(x, y); 
227 chars
13 lines

This will plot a circle centered at (0,0) with radius 1 and resolution 100.

related categories

gistlibby LogSnag