python - 有没有更简单的方法在 Matlab 中构造 Mandelbrot 集?

标签 python matlab matrix

下面显示的代码用于绘制 Mandelbrot set ,我认为我的代码在构造 Matrix M 时有点冗余。在 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 已经超过了你的阈值,并继续只对剩余的点进行迭代(这就是索引 indind2 在下面的代码中):

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

enter image description here

关于python - 有没有更简单的方法在 Matlab 中构造 Mandelbrot 集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20441659/

相关文章:

python - Python 2.7 中的 FFT 合并两个代码

python - 使用python脚本远程访问Django中的sqlite3

带色 block 的 Matlab 图像图例

java - 将 vector 从 Matlab 传递到 Scala 类

matlab在获取pointgrey图像时崩溃

python - 高效计算 numpy/scipy 中的交换矩阵

python - 如何绘制这个有很多函数的图的图例?

python - 如何将单个电位计值转换为 R、G、B?

python - 如何在 Linux 上修复 Python 中的 Except 错误

java - 在java中构建项目-项目矩阵