%MANDEL4 Fourth Mandelbrot file.
% Changes made: write "1i" instead of "i".
% Preallocate Z to correct size.
% Don't refer to "r" outside its for-loop.
% Vectorize final calculation of Z.
% Use LINSPACE instead of direct allocation.
clear
xmax=2;
steps=300;       % Points in each direction?
maxiter=64;      % How many steps per point?

% Initialization
Z = zeros(steps);  % Z is steps-by-steps.
X = linspace(-xmax,xmax,steps);
Y = X;

for m=1:steps
  c = 1i*(Y(m));  % What y value to use?
  for n=1:steps
    c = X(n) - .5 + 1i*imag(c);  % What x value?
    z = c;
    rmax = maxiter;
    for r = 0:maxiter
      z = z*z + c;    % Fractal calculation
      if abs(z)>2     % Stop if outside circle.
        rmax = r;
        break
      end
    end
    Z(m,n) = rmax;  % Color = #iter.
  end
end

Z = sqrt(Z/maxiter);  % Vectorized calculation.

% Plotting commands.  Scale colormap to data.
imagesc(Z)
axis off, axis equal