When I was young, I was introduced to a simple pattern to draw when bored (some include Pascal's triangle and random spirals). To draw this pattern, one needs to start with the four sides of a square, then continue to draw a fifth line so that it forms an acute triangle with the already drawn sides. Essentially, it is a rotated and scaled down square inside of the original square. This pattern is then continued for indefinitely many embedded squares. In my experiences with MATLAB so far I have come across the line plotting function, and of course what better use than this.
My class was also supposed to be learning recursion so I made the initial code to be recursive. As always, though, recursion is pretty much useless due to its inefficiency, unless the problem is mathematically complex and cannot be defined without recursion. Thus the code presented here uses a for loop. Converting it into a recursive function should be quite trivial, as all the calculations are the same.
This code is a function to be run in MATLAB.
function squares(n,f) %inputs: n- number of squares to draw; f- fraction of side length on which the next square's vertex will be drawn (0-1 exclusive) axis square hold on a=[0 1]; b=[1 1]; c=[1 0]; d=[0 0];%initial square coordinates for(n=1:n) plot([a(1) b(1) c(1) d(1) a(1)],[a(2) b(2) c(2) d(2) a(2)]); e=a; a=a+((b-a))*f;%scaling for next square b=b+((c-b))*f; c=c+((d-c))*f; d=d+((e-d))*f; end hold off end
Click on the image to view full resolution. These are scaled down by your browser.
Starting with an elementary pattern, in which the vertices of the inner square are at midpoints of the outer (fraction=0.5), this pattern is obtained, as expected.
Here fractions of 0.75, then 0.2, then 0.05 are used. Note that numbers closer to 0 or 1 will yield a finer grid (0.5 is the worst resolution), while above 0.5 will have a different perceived spin direction than values below 0.5.
For this, a bit of an adventure. With values below 0 or above 1, the square pattern evolves outside of the starting square, rather than inside of it. Notice that the middle square is properly oriented while the ones around it are curved. Fractions significantly above or below 1 or 0, yield strange results, such as the third photo with a fraction of 1.5. After only 25 squares, notice the scale on the figure. It is huge!
After looking at the resulting curves, some interesting properties are evident. One is that every line is a tangent to one of the four 'curves' and is perpendicular to another 'curve'. This clearly rises from the right angles in a square.