
分形是一个很常见的数学问题,一般方法是递归,但是matlab的递归速度比较低下.8层的分形图制作递归的话,大概需要1.9s左右.
下面的代码是迭代方法.
tic;
% 原始三角形顶点,保存在一个n*3*2的数组,第三维共2层,第一层是x,第二层是y
pts(:,:,1) = [0,1,0.5];
pts(:,:,2) = [0,0,0.8];
% 层数
layer = 8;
% 当前层的三角形顶点
cur_pts = pts;
while layer>0
next_pts = []; % 利用当前层顶点计算出来下一层的三角形顶点
for num=1:size(cur_pts,1)
% 利用三顶点计算分形三角形顶点坐标
a = cur_pts(num,1,:);
b = cur_pts(num,2,:);
c = cur_pts(num,3,:);
next_pts(end+1:end+3,:,:) = [a,(a+c)/2,(a+b)/2;
(a+b)/2,b,(b+c)/2;
(a+c)/2,(b+c)/2,c];
end
% 迭代当前层顶点
cur_pts = next_pts;
% 将顶点加入结果数组
pts(end+1:end+size(cur_pts,1),:,:) = cur_pts;
% 层数递减
layer = layer-1;
end
% 作图
patch(pts(:,:,1)',pts(:,:,2)','w');
toc;
No comments :
Post a Comment