用MATLAB运行koch曲线

用MATLAB运行koch曲线,第1张

把以下程序存为koch.m%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%KOCH: Plots 'Koch Curve' Fractal

%

% koch(n) plots the 'Koch Curve' Fractal after n iterations

% e.g koch(4) plots the Koch Curve after 4 iterations.

% (be patient for n>8, depending on Computer speed)

%

% The 'kline' local function generates the Koch Curve co-ordinates using

% recursive calls, while the 'plotline' local function is used to plot

% the Koch Curve.

%

% Copyright (c) 2000 by Salman Durrani (dsalman@wol.net.pk)

%--------------------------------------------------------------------

function []=koch(n)

if (n==0)

x=[01]

y=[00]

line(x,y,'Color','b')

axis equal

set(gca,'Visible','off')

else

levelcontrol=10^n

L=levelcontrol/(3^n)

l=ceil(L)

kline(0,0,levelcontrol,0,l)

axis equal

set(gca,'Visible','off'戚锋)

set(gcf,'Name','Koch Curve')

end

%--------------------------------------------------------------------

function kline(x1,y1,x5,y5,limit)

length=sqrt((x5-x1)^2+(y5-y1)^2)

if(length>limit)

x2=(2*x1+x5)/3

y2=(2*y1+y5)/3

x3=(x1+x5)/2-(y5-y1)/(2.0*sqrt(3.0))

y3=(y1+y5)/2+(x5-x1)/(2.0*sqrt(3.0))

x4=(2*x5+x1)/3

y4=(2*y5+y1)/3

% recursive calls

kline(x1,y1,x2,y2,limit)

kline(x2,y2,x3,y3,limit)

kline(x3,y3,x4,y4,limit)

kline(x4,y4,x5,y5,limit)

else

plotline(x1,y1,x5,y5)

end

%--------------------------------------------------------------------

function plotline(a1,b1,a2,b2)

x=[a1a2]

y=[b1b2]

line(x,y)

%--------------------------------------------------------------------%%%%%%%%%%%%然后在命橘仔核令提示圆掘符处运行koch(5)%%%%%%%%%%%%%%%%%%%%%

Koch曲线程序koch.m

function

koch(a1,b1,a2,b2,n)

%koch(0,0,9,0,3)

%a1,b1,a2,b2为初始线段两纳冲端点坐标,n为迭代次数

a1=0b1=0a2=9b2=0n=3

%第i-1次迭代时由各条线段产生的新四条线段的五点横、纵坐标存储在数组A、B中

[A,B]=sub_koch1(a1,b1,a2,b2)

for

i=1:n

for

j=1:length(A)/5

w=sub_koch2(A(1+5*(j-1):5*j),B(1+5*(j-1):5*j))

for

k=1:4

[AA(5*4*(j-1)+5*(k-1)+1:5*4*(j-1)+5*(k-1)+5),BB(5*4*(j-1)+5*(k-1)+1:5*4*(j-1)+5*(k-1)+5)]=sub_koch1(w(k,1),w(k,2),w(k,3),w(k,4))

end

end

A=AA

B=BB

end

plot(A,B)

hold

on

axis

equal

%由以(ax,ay),(bx,by)为端点的线段生成新的中间三点坐标并把这凳羡五点横、纵坐标依次分别存%储在数组A,B中

function

[A,B]=sub_koch1(ax,ay,bx,by)

cx=ax+(bx-ax)/3

cy=ay+(by-ay)/3

ex=bx-(bx-ax)/3

ey=by-(by-ay)/3

L=sqrt((ex-cx).^2+(ey-cy).^2)

alpha=atan((ey-cy)./(ex-cx))

if

(ex-cx)<0

alpha=alpha+pi

end

dx=cx+cos(alpha+pi/3)*L

dy=cy+sin(alpha+pi/3)*L

A=[ax,cx,dx,ex,bx]

B=[ay,cy,dy,ey,by]

%把由函数sub_koch1生成的五点横、纵坐标A,B顺次划分为四组,分别对应四条折线段中

%每条线段两端点的坐枣茄拍标,并依次分别存储在4*4阶矩阵k中,k中第i(i=1,2,3,4)行数字代表第%i条线段两端点的坐标

function

w=sub_koch2(A,B)

a11=A(1)b11=B(1)

a12=A(2)b12=B(2)

a21=A(2)b21=B(2)

a22=A(3)b22=B(3)

a31=A(3)b31=B(3)

a32=A(4)b32=B(4)

a41=A(4)b41=B(4)

a42=A(5)b42=B(5)

w=[a11,b11,a12,b12a21,b21,a22,b22a31,b31,a32,b32a41,b41,a42,b42]

到分形艺术网看看吧


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12402254.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存