% Reset Matlab
clear
clc
close all

% Define parameters
sigma = 12;
beta = 6/3;
rho = 27;

% Initialise function
f = @(t,a) [-sigma*a(1) + sigma*a(2); rho*a(1) - a(2) - a(1)*a(3); -beta*a(3) + a(1)*a(2)];

% Solve numerically using ode45
[t,a1] = ode45(f,[0 100],[1 1 1]);     

% Define figure properties
fig = figure;
hold on
axis([-50 50 -50 50 0 50])
axis off

% Plot solution
plot3(a1(:,1),a1(:,2),a1(:,3),'k')
drawnow


%% GIF
% Rotate and get frame. Append into structure
for i = 1:720
	camorbit(0.5,0.5)
	drawnow
    frame = getframe(fig);
    im{i} = frame2im(frame);
end

% Save as GIF
filename = 'lorentzSys.gif'; % Specify the output file name
for idx = 1:length(im)
    [A,map] = rgb2ind(im{idx},256);
    if idx == 1
        imwrite(A,map,filename,'gif','LoopCount',Inf,'DelayTime',1e-36);
    else
        imwrite(A,map,filename,'gif','WriteMode','append','DelayTime',1e-36);
    end
end

%% 2 solutions
fig2 = figure;
hold on
axis([-50 50 -50 50 0 50])
axis off

% Plot solution
lh1 = plot3(a1(:,1),a1(:,2),a1(:,3),'r');

% Solve numerically using ode45
[t,a2] = ode45(f,[0 100],[1 1+1e-4 1]);

% Plot solution
lh2 = plot3(a2(:,1),a2(:,2),a2(:,3),'b');

% Change opacity of points
lh1.Color(4) = 0.1;
lh2.Color(4) = 0.1;

drawnow
%% GIF
% Rotate and get frame. Append into structure
for i = 1:2*720
	camorbit(0.5,0.25)
	drawnow
    frame2 = getframe(fig2);
    im2{i} = frame2im(frame2);
end

% Save as GIF
filename2 = 'lorentzSys2.gif'; % Specify the output file name
for idx2 = 1:length(im2)
    [A2,map2] = rgb2ind(im2{idx2},256);
    if idx2 == 1
        imwrite(A2,map2,filename2,'gif','LoopCount',Inf,'DelayTime',1e-36);
    else
        imwrite(A2,map2,filename2,'gif','WriteMode','append','DelayTime',1e-36);
    end
end