%MANDEL_UNROLL Final 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.
% Unroll complex number arithmetic to reals.
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_i = Y(m);  % What y value to use?
  for n=1:steps
    c_r = X(n) - .5;  % What x value?
    z_r = c_r;
    z_i = c_i;
    rmax = maxiter;
    for r = 0:maxiter
      zr_temp = z_r*z_r - z_i*z_i + c_r;
      zi_temp = 2*z_r*z_i + c_i;
      z_r = zr_temp;
      z_i = zi_temp;
      if z_r*z_r + z_i*z_i > 4  % Stop?
        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