Skip to content

Instantly share code, notes, and snippets.

@Kuxe
Last active May 1, 2017 15:39
Show Gist options
  • Save Kuxe/58266231e2205a1eff21943a1040cfe1 to your computer and use it in GitHub Desktop.
Save Kuxe/58266231e2205a1eff21943a1040cfe1 to your computer and use it in GitHub Desktop.
Matlab script for generating a movie showing the "Chaos game" explained by Numberphile https://www.youtube.com/watch?v=kbKtFN71Lfs
clc;
clear;
% CONSTANTS
N_ITERS = 1000000;
IM_DIM = 1024;
N_VERTICES = [3, 4, 5, 7, 20, 50];
TOT_VERTS = length(N_VERTICES);
N_FRAMES_PER_FRACTAL = 30*3;
TOT_FRAMES = N_FRAMES_PER_FRACTAL * TOT_VERTS;
color = zeros(IM_DIM, IM_DIM, 3);
movie = zeros(IM_DIM, IM_DIM, 3, TOT_FRAMES);
frame = 1;
for n_verts = N_VERTICES
% Generate #n_verts equidistant points on unit circle centered at [1,1]
for i=1:n_verts
vertices(i, :) = (([cos(i*(2*pi)/n_verts), sin(i*(2*pi)/n_verts)])+1)/2;
end
%Get a random starting point
point = rand(1,2);
elapsed=1;
for i=1:N_FRAMES_PER_FRACTAL
tic;
weight = min(i / (N_FRAMES_PER_FRACTAL+1), 1-1/sqrt(n_verts+1));
%Generate the next point and color it as function of i,j
for j=1:N_ITERS
point = point + (vertices(randi(n_verts), :)-point) * weight;
color(ceil(point(1)*IM_DIM), ceil(point(2)*IM_DIM), :) = [(j/N_ITERS)^2, 1-(j/N_ITERS + i/N_FRAMES_PER_FRACTAL)/2, i/N_FRAMES_PER_FRACTAL];
end
movie(:, :, :, frame) = flipud(color);
color = zeros(IM_DIM, IM_DIM, 3);
frame = frame + 1;
fprintf('Progress: %1.2f%%, estimate time: %s...\n', frame/TOT_FRAMES*100, datestr(((TOT_FRAMES-frame)*toc)/(24*60*60), 'HH:MM:SS'));
end
end
%Start a movieplayer and show the movie
implay(movie);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment