%% define initial conditions and time vector
state0 = [2.0, 3.0, 4.0];
t = 0:.01:30;

%% run the simulation
[t,state] = ode45('MyLorenz', t, state0);

%% plot the resuling state?space trajectory in 3D
plot3(state(:,1), state(:,2), state(:,3))
xlabel('X');
ylabel('Y');
zlabel('Z');
grid on

%% change initial conditions and re-simulate
% original simulation
state0 = [2.0, 3.0, 4.0];
t = 0:.01:30;
[t,state] = ode45('MyLorenz', t, state0);

% plot the resuling state?space trajectory in 3D
plot3(state(:,1), state(:,2), state(:,3), 'b-', 'linewidth', 2)
xlabel('X');
ylabel('Y');
zlabel('Z');
grid on

%% now re?run with very small change in initial conditions
delta = 0.0001;
state0 = [2.0+delta, 3.0, 4.0];
t = 0:.01:30;
[t2,state2] = ode45('MyLorenz', t, state0);
hold on
plot3(state2(:,1), state2(:,2), state2(:,3), 'r-', 'linewidth', 2)

%% compute distance between two state trajectories and plot
dist = sqrt(sum((state2-state).^2,2));
figure
plot(t,dist,'b-','linewidth',2)
xlabel('TIME (sec)')
ylabel('DISTANCE')
grid on

%% make an animation
figure
plot3(state(:,1),state(:,2),state(:,3),'Color',[.6 .6 1],'linewidth',1);
hold on
plot3(state2(:,1),state2(:,2),state2(:,3),'Color',[1 .6 .6],'linewidth',1);
p1 = plot3(state(1,1),state(1,2),state(1,3),'b.','markersize',30);
p2 = plot3(state2(1,1),state2(1,2),state2(1,3),'r.','markersize',30);
tt = title('0.0');
step = 1;
view([32 22])
grid on
xlabel('X'); ylabel('Y'); zlabel('Z');
drawnow
for i=1:step:length(t)
    set(p1,'XData',state(i,1));
    set(p1,'YData',state(i,2));
    set(p1,'ZData',state(i,3));
    set(p2,'XData',state2(i,1));
    set(p2,'YData',state2(i,2));
    set(p2,'ZData',state2(i,3));
    set(tt,'String',sprintf('%6.2f',t(i)));
    drawnow
end
