MATLAB: Plotting Sierpinski’s triangle

doit4mehomeworkMATLAB

Sierpinski’s triangle can be implemented in MATLAB by plotting points iteratively according to one of the following three rules which are selected randomly with equal probability.
  • Rule 1: x=05.*x y=0.5*y
  • Rule 2: x=0.5*x+.25 y=0.5*y+ sqrt(3)/4
  • Rule 3: x=0.5x+.5 y=.5*y
Write a script that calculates the x and y vectors and then plots y versus x as individual points.
Start with x1=0 and y1=0. Run the program three times, with 100, 1000, and 10000 iterations. Print all three plots.
I do not know where to start. I am thinking if and for loops but not sure.

Best Answer

Almost forgot to post my code, hope this helps those who bother to search a little bit
clf
hold on
N=100000;
x=zeros(1,N);y=x;
for a=2:N
c=randi([0 2]);
switch c
case 0
x(a)=0.5*x(a-1);
y(a)=0.5*y(a-1);
case 1
x(a)=0.5*x(a-1)+.25;
y(a)=0.5*y(a-1)+sqrt(3)/4;
case 2
x(a)=0.5*x(a-1)+.5;
y(a)=0.5*y(a-1);
end
end
plot(x,y,'.')
title('Sierpinski’s triangle made in matlab by Paulo Silva')
legend(sprintf('N=%d Iterations',N))
Related Question