MATLAB: Write a function that produces a plot for the Cantor Set

cantorcantor sethomeworkMATLABset

The Cantor Set is an image that looks like this: http://library.thinkquest.org/2647/media/cantor.jpg
I am asked to write a function that takes the number of iterations(n) as input and produces the desired plot. I am told that the number of rows in each Matrix of n iterations is equal to the number of line segments.
I first started off doing this problem by finding a relationship between the number of iterations (n) and the number of rows (rn). Each matrix of n interation has the same number of columns but different number of rows, and I found the relationship between rn and n to be: rn=(2^n)
I then wrote out the matrices for n=0,1, and 2 iterations and got the following: When n=0, M equals [0 1]. When n=1, M equals [0 1/3; 2/3 1]. When n=2, M equals [0 1/9; 2/9 1/3; 2/3 7/9; 8/9 1] So the relationship between Mn and Mn-1 is the top half of the matrix Mn (first rn/2) is equal to the previous matrix Mn-1 times 1/3. And the bottom half of the matrix Mn is equal to the top half plus 2/3. I have found the relationships but I am not quite certain on how to write the script to graph the plot. I have started my function with the first iteration of Mprev=[0 1] and I am not sure how to add the additional rows for the other iterations. Please help! Thanks!!

Best Answer

Dear Jerry, here is the code which plotting Cantor Set:
n = input('Input number of iterations:');
a = cell(1,n);
for j = 1:n
a{j} = linspace(0, 1, 2^j);
end
m = n;
for j = 1:n
b = a{j};
l = ones(1, length(b)) * m;
plot(b, l, 'ro-'), hold on
m = m - 1;
end
xlim([-0.1 1.1]), ylim([0 n+1])
I hope it helps. Good luck!