koch曲线与koch雪花的MATLAB实现
代码
1 % 2016-4-3 2 function koch(Ax, Ay, Bx, By) 3 % 控制递归深度 4 Deepth = 20; 5 % 控制图画大小 6 Size = 100; 7 if ((Bx-Ax)^2 + (By-Ay)^2) < Deepth 8 plot([Ax, Bx], [Ay, By], '-r') 9 hold on 10 axis([0 Size 0 Size]); 11 else 12 Cx = Ax + (Bx-Ax)/3; 13 Cy = Ay + (By-Ay)/3; 14 Dx = Bx - (Bx-Ax)/3; 15 Dy = By - (By-Ay)/3; 16 17 koch(Ax, Ay, Cx, Cy); 18 koch(Dx, Dy, Bx, By); 19 20 L = sqrt((Dx-Cx)^2 + (Dy-Cy)^2); 21 alpha = atan((Dy-Cy)/(Dx-Cx)); 22 % 数学 23 if (alpha>=0 && Dx-Cx<0) || (alpha<0 && (Dx-Cx)<0) 24 alpha = alpha + pi; 25 end 26 27 Ex = Cx + cos(alpha + pi/3)*L; 28 Ey = Cy + sin(alpha + pi/3)*L; 29 30 koch(Cx, Cy, Ex, Ey); 31 koch(Ex, Ey, Dx, Dy); 32 end 33 end 34 35 % matlab的单步调试有助于理解该递归 36 % 可通过设置断点观察图形是如何一步一步被画出来的
koch曲线
koch雪花