make a function recursive (koch snowflake)

21 ビュー (過去 30 日間)
Mireia Boneta Camí
Mireia Boneta Camí 2020 年 10 月 25 日
回答済み: Alan Stevens 2020 年 10 月 25 日
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

採用された回答

Alan Stevens
Alan Stevens 2020 年 10 月 25 日
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 件)

カテゴリ

Help Center および File ExchangeCalendar についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by