下面显示的代码用于绘制曼德尔布罗特集 http://en.wikipedia.org/wiki/Mandelbrot_set,我认为我的代码对于构造有点冗余Matrix M
. In Python我知道有一种干净的方法可以做到这一点,
M = [[mandel(complex(r, i)) for r in np.arange(-2, 0.5,0.005) ] for i in np.range(-1,1,0.005)]
Matlab中有类似的方法吗?
function M=mandelPerf()
rr=-2:0.005:0.5;
ii=-1:0.005:1;
M = zeros(length(ii), length(rr));
id1 = 1;
for i =ii
id2 = 1;
for r = rr
M(id1, id2) = mandel(complex(r,i));
id2 = id2 + 1;
end
id1 = id1 + 1;
end
end
function n = mandel(z)
n = 0;
c = z;
for n=0:100
if abs(z)>2
break
end
z = z^2+c;
end
end
您可以完全避免循环。你可以进行迭代z = z.^2 + c
以矢量化的方式。为了避免不必要的操作,在每次迭代时跟踪哪些点c
已经超过了你的阈值,并且只继续迭代剩余的点(这就是索引的目的ind
and ind2
在下面的代码中):
rr =-2:0.005:0.5;
ii =-1:0.005:1;
max_n = 100;
threshold = 2;
c = bsxfun(@plus, rr(:).', 1i*ii(:)); %'// generate complex grid
M = max_n*ones(size(c)); %// preallocation.
ind = 1:numel(c); %// keeps track of which points need to be iterated on
z = zeros(size(c)); %// initialization
for n = 0:max_n;
z(ind) = z(ind).^2 + c(ind);
ind2 = abs(z(ind)) > threshold;
M(ind(ind2)) = n; %// store result for these points...
ind = ind(~ind2); %// ...and remove them from further consideration
end
imagesc(rr,ii,M)
axis equal
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)