Search code examples
matlabmatlab-figurefractals

How to get color gradient for Newton Method basin of attraction fractal


I am using MATLAB to go through a NxN grid in the complex plane, the x's are the real component and the y's are the imaginary component. For each point on this grid I am using it as a starting point for Newton's Method. Depending on which root it converges to it is assigned a number. This number is used with pcolor to plot the fractal.

It plots nicely, however, I want to also plot the color darkness depending on how long it takes to converge to the root. I am having trouble with pcolor. I was able to get the 3 colors for the 3 roots but I am not quite sure how to add more colors so that it is more descriptive.

Here is the code to get the plot after I have
xp - array of x points
yp - array of y points
col - NxN matrix that has either 1, 2, 3 (corresponds to which root)

% thresholds for color
caxis([1 3]); 

% sets colors Red, Green, Blue
mycolors = [1 0 0; 0 1 0; 0 0 1];
colormap(mycolors);

% real component on x and imaginary component on y
h=pcolor(xp, yp, col');
set(h, 'LineStyle', 'none' );

So, how can I get there to be a gradient in pcolor, it seems that pcolor just kind of figures out all the colors itself. And caxis only allows boundaries for 2 colors.

Let me know if you want to see the full code of this program. Thank you


Solution

  • Add the number of iterations it took to get to convergence as a color. Define the colors in HSV, and make the number of iterations map to the value S of HSV. That will give you a nice and meaningful color gradient without really changing the colors.

    The pseudocode is:

    For that, generate your 3 colors mycolors as you do. Change their color space as mycolorshsv=rgb2hsv(mycolors);

    What you want now is to generate a bunch (your choice) of colors per color.

    mycolorshsv=repelem(mycolorshsv,N,1);
    

    Now lets generate N gradients per color.

    mycolorshsv(    1:  N,2)=linspace(0,1,N);
    mycolorshsv(  N+1:2*N,2)=linspace(0,1,N);
    mycolorshsv(2*N+1:3*N,2)=linspace(0,1,N);
    

    You want e.g. the longest iteration you obtained maxiter to be the brightest. We need to transform your col matrix from [1,2,3] to our current range now. For that, just

    col=(col-1)*N+1; % make 1=>1, 2=>N, 3=>2*N;
    col=col+iteration_matrix; %max(iteration_matrix) must be maxiter. You may want to normalize so min(iteration_matrix) is 0
    

    Now simply set the colormap(mycolors);, and I would use imagesc instead of pcolor, but its less important.

    Play with the range, and limits of the colro values for nicer maps. Often non-linear maps are also used, where a function f is applied to the iteration values, such as the sigmoid.

    This is the technique used for the newton fractals you can find in wikipedia, such as:

    enter image description here