clf ; clear
xmin = -2.0;
xmax = +2.0;
ymin = -2.0;
ymax = +2.0;
nPoints = 4000;
fstop = 1e-06;
x = linspace(xmin, xmax, nPoints);
y = linspace(ymin, ymax, nPoints);

for i=1:nPoints
    for j=1:nPoints 
        z = complex(x(i),y(j)); % this converts (x,y) to a complex number 'z'
        
        it_max = 300;            
        for n = 1:it_max
            f = 35*z^9-180*z^7+378*z^5-420*z^3+315*z;
            if (abs(f)<fstop)
                break;
            end
            z = z - (35*z^9-180*z^7+378*z^5-420*z^3+315*z)/(315*z^8 -1260*z^6 + 1890*z^4 -1260*z^2 + 315);
         end

        %store the results in the matrix ZZ(nPoints,nPoints)
        if (n==it_max) ZZ(j,i)=0;  % make it '0' for blue if |z| is small and series has not diverged
        else ZZ(j,i)=n;            % make it '1' for red  if |z| is large and series has diverged
        end

    end
    fprintf('i= %d of %d points in X direction: x= %f\n',i,nPoints,x(i));
end
% plot and gif creation

m = max(max(ZZ));
gif_frame_counter = 0;
for i=1:1000
    ZZ = mod(ZZ+1,m); 
    imagesc(x,y,ZZ);         
    set(gca,'YDir','normal');
    if mod(i+9,10) == 0
        gif_frame_counter = gif_frame_counter + 1;           
        saveas(gcf, ['newton_',sprintf('%03d',gif_frame_counter),'.png'])        
        pause(0.001)   
   end   
end

% imagesc(x,y,ZZ); % plot the image
% set(gca,'YDir','normal');
