% Mandelbrot plotter
% A Matlab script which plots the Mandelbrot set.
% Written by Toby Newman for the sheer love of it.
% http://www.asktoby.com
% ======================
% Clear the workspace
clear; clc;
% Create a menu allowing the user to select a quality setting.
quality = menu('select quality', 'coarse and fast', 'medium', 'detailed and slow');
% The menu returns 1, 2 or 3. Translate these values into useful detail
% quality values:
quality = 0.05/(quality*2);
% Turn on 'Hold' to allow the Mandelbrot set to be drawn onto the complex
% plane, pixel by pixel, as the program iterates.
hold on;
% Echo progress to console
disp('Working...')
% Work through every value in the complex plane. The accuracy is defined by
% the 'quality' variable which was chosen using a menu above. This defines
% the skipped space between worked-out values.
% First, work through all real values in increments of the value 'quality'
% It is known that real values which are part of Mandelbrot's set go
% from -2.1 to 1 so this sets the start/end points.
for m = -2.1:quality:1 
    % Next, work through all imaginary values in increments of the value 'quality'
    % It is known that imaginary values which are part of Mandelbrot's
    % set go from -1.2 to 1.2 so this sets the start/end points.
    for n = -1.2:quality:1.2
        % create a complex value on the complex plane.
        Z0 = complex(m,n);
        % Run the first step of the iterative formula required to decide
        % if this value will tend to infinity or not
        Zn = Z0^2 + Z0;
        % Repeat the above, iterating from 1 to 50 to give the complex
        % number a chance to go to infinity, or to settle.
        for iterations = 1:1:50 
            % Run the remaining steps of the iterative formula required to decide
            % if this value will tend to infinity or not
            Zn = Zn^2 + Z0;
        end
        % Check to see if the result is part of the set or if it has gone to
        % infinity
        % If the modulus of the result exceeds 2, the calculation will always,
        % if iterated more, continue on to infinity. Therefore, all the program needs to do is
        % determine that the modulus of the iteration calculation result has 
        % exceeded 2 to declare that it’s not part of the set.
        % Check to see if the modulus (abx(Zn)) is less than 2
        if (abs(Zn)<2)
            % The modulus is less than 2. The value IS part of the
            % Mandelbrot set. Plot it as a pixel on the complex plane.
            plot (Z0);
        end
     end 
end
% Echo progress to console
disp('Done!')
