MATLAB Answers

make a function recursive (koch snowflake)

28 views (last 30 days)
Hello everybody, I have this function to store the points of a koch snowflake and draw them. The problem is that I have done it with loops and not recursively, and I would like to do it recursively. I want to do it with only one input (the number of iterations) and store all the points to the matrix P. Do you have any idea on how to do it? or the pseudo-code or something like this. Thank you very much!
function Koch(n)
%Koch draws Koch snowflake
%n is how many iterations of the creative process we want
% initialize P to an equilateral triangle
P = [ 0 0;
1 0;
cos(-pi/3), sin(-pi/3);
0 0 ];
for iteration=1:n
newP = zeros( size(P,1)*4+1, 2);
for i=1:size(P,1)-1
newP(4*i+1,:) = P(i,:);
newP(4*i+2,:) = (2*P(i,:) + P(i+1,:) )/3;
link = P(i+1,:)-P(i,:);
ang = atan2( link(2), link(1) );
linkLeng = sqrt( sum(link.^2) );
newP(4*i+3,:) = newP(4*i+2,:) + (linkLeng/3)*[ cos(ang+pi/3), sin(ang+pi/3) ];
newP(4*i+4,:) = (P(i,:) + 2*P(i+1,:) )/3;
end
newP( 4*size(P,1)+1,:) = P(size(P,1),:);
P = newP
end
% now join up the points in P
clf; % clear the figure window
plot( P(:,1), P(:,2) ); % plot P
axis equal; % make the x- and y-scale the same
end

  0 Comments

Sign in to comment.

Accepted Answer

Alan Stevens
Alan Stevens on 25 Oct 2020
The following replaces the "for iteration = 1:n" loop with a recursive function
%Koch draws Koch snowflake
%n is how many iterations of the creative process we want
n = 5;
% call recursive Koch function
P = Koch(n);
% plot snowflake
clf; % clear the figure window
plot( P(:,1), P(:,2) ); % plot P
axis equal; % make the x- and y-scale the same
function P = Koch(n)
if n == 1
P = [0 0; 1 0; cos(-pi/3) sin(-pi/3); 0 0];
P = newP(P);
else
P = Koch(n-1);
P = newP(P);
end
end
function Pout = newP(P)
newP = zeros( size(P,1)*4+1, 2);
for i=1:size(P,1)-1
newP(4*i+1,:) = P(i,:);
newP(4*i+2,:) = (2*P(i,:) + P(i+1,:) )/3;
link = P(i+1,:)-P(i,:);
ang = atan2( link(2), link(1) );
linkLeng = sqrt( sum(link.^2) );
newP(4*i+3,:) = newP(4*i+2,:) + (linkLeng/3)*[ cos(ang+pi/3), sin(ang+pi/3) ];
newP(4*i+4,:) = (P(i,:) + 2*P(i+1,:) )/3;
end
newP( 4*size(P,1)+1,:) = P(size(P,1),:);
Pout = newP;
end

  0 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by