(有缺陷的)代码如下:
function fern()
AI = [0 0 ; 0 0.16];
AII = [ 0.85 0.04 ; -0.04 -0.85 ] ;
AIII = [ 0.2 -0.26 ; 0.23 0.22 ] ;
AIV = [-0.15 0.28 ; 0.26 0.24 ];
BI = [ 0 ; 0];
BII = [ 0 ; 1.6];
BIII = [ 0 ; 1.6];
BIV = [0 ; 0.44];
N = 10000;
I = 50;
H = zeros(N,2);
for n=1 : N
x = rand;
y = rand;
T = [x;y];
for i=1 : I
p = rand;
if p < 0.01
%disp('Scheme 1')
S1x = AI*T + BI;
S1y = AI*T + BI;
x = S1x(1);
y = S1y(2);
elseif p < 0.08
%disp('Scheme 2')
S2x = AII*T + BII;
S2y = AII*T + BII;
x = S2x(1);
y = S2y(2);
elseif p < 0.15
%disp('Scheme 3')
S3x = AIII*T + BII;
S3y = AIII*T + BII;
x = S3x(1);
y = S3y(2);
else
%disp('Scheme 4')
S4x = AIV*T + BIV;
S4y = AIV*T + BIV;
x = S4x(1);
y = S4y(2);
end
H(n,1) = x;
H(n,2) = y;
end
end
X = H(:,1);
Y = H(:,2);
plot(X,Y,'.')
我不知道为什么它不起作用。迭代过程不正确吗?我运行代码,然后获得以下图形:
我想,这可能与我的if循环结构的方式有关,因为一切运行正常。或许,我的方案的定义方式,但它们似乎是典型的。
编辑:添加已清理的代码
function fern3()
AI = [0 0 ; 0 0.16];
AII = [ 0.85 0.04 ; -0.04 -0.85 ] ;
AIII = [ 0.2 -0.26 ; 0.23 0.22 ] ;
AIV = [-0.15 0.28 ; 0.26 0.24 ];
BI = [ 0 ; 0];
BII = [ 0 ; 1.6];
BIII = [ 0 ; 1.6];
BIV = [0 ; 0.44];
N = 10000;
I = 50;
H = zeros(N,2);
for n=1 : N
x = rand;
y = rand;
T = [x;y];
for i=1 : I
p = rand;
if p < 0.01
%disp('Scheme 1')
H(n,:) = AI*T + BI;
elseif p < 0.08
%disp('Scheme 2')
H(n,:) = AII*T + BII;
elseif p < 0.15
%disp('Scheme 3')
H(n,:) = AIII*T + BIII;
else
%disp('Scheme 4')
H(n,:) = AIV*T + BIV;
end
end
end
X = H(:,1);
Y = H(:,2);
plot(X,Y,'.')
end
答案 0 :(得分:2)
我不确定你的算法来自哪里。维基百科上的那个效果很好。
function fern
% Barnsley Fern Fractal generator
% Using definition and pseudocode from Wikipedia
% (https://en.wikipedia.org/wiki/Barnsley_fern)
maxI = 1E7;
x = zeros(maxI,1);
y = zeros(maxI,1);
for i = 2:maxI
r = rand;
if (0 <= r) && (r < 0.01)
x(i) = 0;
y(i) = 0.16*y(i-1);
elseif (0.01 <= r) && (r < 0.86)
x(i) = 0.85 * x(i-1) + 0.04 * y(i-1);
y(i) = -0.04 * x(i-1) + 0.85 * y(i-1) + 1.6;
elseif (0.86 <= r) && (r < 0.93)
x(i) = 0.2 * x(i-1) - 0.26 * y(i-1);
y(i) = 0.23 * x(i-1) + 0.22 * y(i-1) + 1.6;
else
x(i) = -0.15 * x(i-1) + 0.28 * y(i-1);
y(i) = 0.26 * x(i-1) + 0.24 * y(i-1) + 0.44;
end
end
plot(x,y,'.', 'Color', [79, 121, 66]/256, 'markersize', 0.1)
end