
%  ifs2d.m
%  routine to produce plots of attractors sets of 2D 
%  iterated function systems with probabilities
%  using the random iteration algorithm, or "Chaos Game"

%  nmaps IFS maps w(i) = A(i)*x + b(i), i=1..nmaps, with probabilities p(i)

%  the attractor A of an IFS is presented as a scatter plot
%  in the region [xmin,xmax] X [ymin,ymax]
%  (the user may have to adjust these values accordingly)

nmaps=3;
niter=20000;
xmin=0.0;
xmax=1.0;
ymin=0.0;
ymax=1.0;
kndx=zeros(1,1,'uint8');

% these vectors will store the x and y coordinates of the points
% generated on the attractor

xx=zeros(niter,1);
yy=zeros(niter,1);

% these vectors store the IFS parameters

a11=zeros(nmaps,1);
a12=zeros(nmaps,1);
a21=zeros(nmaps,1);
a22=zeros(nmaps,1);
b1=zeros(nmaps,1);
b2=zeros(nmaps,1);
p=zeros(nmaps,1);

%  input IFS parameters from a data file

[a11,a12,a21,a22,b1,b2,p] = textread('ifs2d.dat','%f %f %f %f %f %f %f',nmaps);

%  start with (0,0) and iterate first IFS map until points get close to its
%  fixed point (which is a point on the attractor)

x=0.0;
y=0.0;
for i=1:50
    x1=a11(1)*x + a12(1)*y + b1(1);
    y1=a21(1)*x + a22(1)*y + b2(1);
    x=x1;
    y=y1;
end

% now continue random iteration of IFS over points on attractor
% here, the IFS maps are chosen with equal probabilities
% this program can be modified so that the ith IFS map is chosen
% with probability p(i)

for i=1:niter

    xran=rand;
    kndx=round(nmaps*xran+0.5);
    kk(i)=kndx;
    x1=a11(kndx)*x + a12(kndx)*y + b1(kndx);
    y1=a21(kndx)*x + a22(kndx)*y + b2(kndx);
    x=x1;
    y=y1;
    xx(i)=x;
    yy(i)=y;
    
end

% plot the attractor

figure(1)
scatter(xx,yy,'.'),xlim([xmin xmax]),ylim([ymin  ymax]);
    
 
