Lozansky
Lozansky

Reputation: 374

Filling Sierpinski triangle

I wish to create filled Sierpinski triangles. Instead my code produces a Sierpinski triangle with filled background. In other terms, how can I inverse the colors? See code below:

function out = sierpinski(a, b, c, n)
M1 = (a+b)/2;
M2 = (b+c)/2;
M3 = (a+c)/2;
k = [M1(1), M2(1), M3(1)];
m = [M1(2), M2(2), M3(2)];
if n==0
    out.x=[a(1), b(1), c(1)];
    out.y=[a(2), b(2), c(2)];
    patch(out.x,out.y,'r')  % choosing the color red in this case
else
    s1 = sierpinski(a,M1,M3,n-1);
    s2 = sierpinski(M1,b,M2,n-1);
    s3 = sierpinski(M3,M2,c,n-1);
    out = [s1 s2 s3];
end

If you wish the run the code yourself, here is an arbitrary input: sierpinski([0 0], [1 0], [.5 .8], 2) First picture below is what I get, second is what I want (apart from the black background). What I get

What i want

Upvotes: 2

Views: 760

Answers (1)

BillBokeey
BillBokeey

Reputation: 3511

Your function is a recursive function, meaning that it will call itself again from its inner code, while n>0 .

Now that this is set, let's try to understand what your code does and compare it to what you want your code to do.

Step 1 :

sierpinski([0 0], [1 0], [.5 .8], 0) ;

Here, as n=0, you won't evaluate the recursive calls.

What your code does :

a) Calculate the coordinates of the middles of the vertices constituting the input triangle

b) Draw the triangle corresponding to the input points

What you want your code to do :

a) Calculate the coordinates of the middles of the vertices constituting the input triangle

b) Draw the triangle corresponding to these MIDDLES.

Step 2 :

sierpinski([0 0], [1 0], [.5 .8], 1) ;

What your code does :

a) Calculate the middles of the vertices

b) Recursively call the function with the 3 outer triangles formed by picking 2 middles and 1 corresponding input point.

c) No plot

d) The recursive calls will patch red the 3 outer triangles.

You should be starting to see the problem. The only thing you need to do is :

1) Move your call to patch outside of the if check so that it will be called everytime.

2) Change the inputs you pass to patch so that it plots the middles of the vertices of the input triangle.

So it's something along the lines of :

function out = sierpinski(a, b, c, n)
M1 = (a+b)/2;
M2 = (b+c)/2;
M3 = (a+c)/2;
k = [M1(1), M2(1), M3(1)];
m = [M1(2), M2(2), M3(2)];
patch(k,m,'r')  % choosing the color red in this case
if n==0
    out.x=[a(1), b(1), c(1)];
    out.y=[a(2), b(2), c(2)];
else
    s1 = sierpinski(a,M1,M3,n-1);
    s2 = sierpinski(M1,b,M2,n-1);
    s3 = sierpinski(M3,M2,c,n-1);
    out = [s1 s2 s3];
end

Upvotes: 1

Related Questions