- /
-
Collatz Tree
on 30 Nov 2023
- 16
- 18
- 1
- 0
- 665
drawframe(1);
Write your drawframe function below
function drawframe(f)
%% Draw the Collatz tree
% initialize cycle
G = graph([1 2],[2 4]);
% starting number
n = 4;
% depth
depth = round(f^(3/4));
% do recursion
G = collatz(G,n,depth);
% remove auto-added isolated nodes
isolated_nodes = find(degree(G) == 0);
G = rmnode(G,isolated_nodes);
% create figure
fig = figure;
colormap cool
p = plot(G);
layout(p,'layered','direction','right')
for j = 1:G.numedges
edge = table2array(G.Edges(j,:));
labelnode(p,edge,string(edge));
end
p.NodeCData = cellfun(@str2double, p.NodeLabel);
p.MarkerSize = 4;
p.LineWidth = 1;
p.NodeLabel = {};
p.EdgeColor = 'w';
cbar = colorbar;
cbar.Color = 'w';
cbar.FontSize = 12;
axis off
fig.Color = 'k';
end
%% Collatz conjecture rule
function G = collatz(G,n,depth)
if mod(n,3) == 2
R = [2*n, (2*n-1)/3];
else
R = 2*n;
end
depth = depth -1;
if ~depth
return
end
for j = 1:length(R)
G = G.addedge(n,R(j));
G = collatz(G,R(j),depth);
end
end