function EN40_HW1_2018
%  EN40 2018 Homework 1  Solutions
%  13 POINTS TOTAL

close all    % This closes any open figure windows

%% Problem 8: Linearly spaced points from -5pi/12 to pi/16  
%  Other methods are fine too.
 for i=1:500
    t(i) = -pi*5/12*(500-i)/499+16*pi*(i-1)/499; 
 end
 
%  [1 POINT]
 
 %%    Problem 9 - Parametric Plot  

 x = exp(-0.1.*t).*sin(t);
 y = exp(-0.1.*t).*cos(2*t);
 figure
 plot(x,y,'Color',[1,0,0],'LineWidth',2);
 grid('on');
 ylabel('y');
 xlabel('x');
 title('Problem 2 - parametric plot');

% [2 POINTS + 1 point credit for labeling the plot]  
 
%%     Problem 10 - Matrix exercises
%      The 'disp' and 'compose' functions are not covered in the tutorial
%      Any format for the display is OK
%
disp('Magic 5x5 matrix');
A = magic(5)                 %[0.5 POINTS]

disp('Sum the rows');        %[0.5 POINTS]
for row=1:5
    rowsum = sum(A(row,:));
    str = compose('row number: %3d Sum: %3d', row,rowsum);
    disp(str);
end

disp(' ');
disp(' Sum the columns');    %[0.5 POINTS]
for col=1:5
    colsum = sum(A(:,col));
    str = compose('Column number: %3d Sum: %3d', col,colsum);
    disp(str);
end

disp(' ');
disp('The eigenvalues');     %[0.5 POINTS]
disp(eig(A));
disp(' ');
str = compose('Sum of the eigenvalues %3g', sum(eig(A)));
disp(str);

 
%%     Problem 11 - Game of Life

A = zeros(50);
A(4:8,23:27) = 1;
A(18:27,23:27) = 1;
A(39:48,24:26) = 1;
for k=1:184
   A = update_matrix(A);
   imshow(1-A,'Initialmagnification',800);
   pause(0.1);
end

%  [3 POINTS]

%% Problem 12 - Solve the Hindmarsh-Rose equations

initial_w = [-1.;-12;2];
I = 2;
r = 0.001;
[times,sols] = ode45(@(t,w) neuron(t,w,I,r), [0,1500],initial_w);
figure
plot(times,sols(:,1),'Color',[1,0,0],'LineWidth',1);
 grid('on');
 ylabel('Action potential (normalized)');
 xlabel('Time (milliseconds)');
 title('Neuron bursts for I=2, r=0.001');

 I = 3.25;
r = 0.005;
options = odeset('RelTol',0.00001);
[times,sols] = ode45(@(t,w) neuron(t,w,I,r), [0,1500],initial_w,options);
figure
plot(times,sols(:,1),'Color',[1,0,0],'LineWidth',1);
 grid('on');
 ylabel('Action potential (normalized)');
 xlabel('Time (milliseconds)');
 title('Neuron bursts for I=3.23, r=0.005');

 % [3 POINTS + 1 POINT for labeling plots]
 
 
end

function newA = update_matrix(A)
%  Updates the matrix A according to the rules of 'Life'
[n,m] = size(A);
newA = A;
for i=2:n-1
    for j=2:m-1
        s = sum(sum(A(i-1:i+1,j-1:j+1)));
        if (s==3) 
            newA(i,j) = 1;
        elseif (s==4)
            newA(i,j) = A(i,j);
        else
            newA(i,j) = 0;
        end
    end
end
end

function dwdt = neuron(t,w,I,r)
%  Differential equations for the Hindmarsh Rose equation 
   V = w(1);  y = w(2); z = w(3);
   
   dVdt = I + y + 3*V^2 - V^3 - z;
   dydt = 1-5*V^2-y;
   dzdt = r*(4*V-z+32/5);
 
   dwdt = [dVdt;dydt;dzdt];
end
