function en4_hw1
%  Solutions to 2009 EN4 Homework #1
% MAX SCORE 15 POINTS

% You can award up to 5 points extra
% credit if anyone does anything clever
% - e.g. working out how to label the plots,
% finding a new way to solve

% 1. Loop to create a vector v
for i=1:100 v(i) = 2*pi*(i-1)/99; end

%[2 POINTS]
% 2. Plot of y = cos^2(x)
% Other solutions are fine too, e.g. using a loop
figure
y = cos(v);
y = y.^2;
plot(v,y)

%[2 POINTS]

%                | cos^2(x)   sin(x)>0.707
% 3. plot of y = |
%                | sin^2(x)   sin(x)<0.707

% Here is one solution - there are many
% others 
% We use 1000 points to make the plot look
% nice and symmetric. But this is not necessary
% most people used 100 points
for i = 1:1000
    v(i) = 2*pi*(i-1)/999;
    if (sin(v(i))<0.707)
        y(i) = cos(v(i))^2;
    else
        y(i) = sin(v(i))^2;
    end
end

figure
plot(v,y)

%[3 POINTS]

% 4. Integration of Gompertz equation
clear('v');

tau = 15; % Time constant, in days
V0 = 2;   % Terminal volume
v_initial = 0.01; % initial volume
[t,V] = ode45(@growthrate,[0,100],v_initial);

figure
plot(t,V)

%[3 POINTS]

% 5. Integration of equations of motion for spring-mass system

m = 1500; %mass, in kg
k = 25000; % stiffness, in N/m
lambda = 300; % viscous dissipation, in Ns/m
F0 = 1000; % Force amplitude, in N
w = 10; % Forcing frequency, in rad/sec
y0 = [0;0];   % Initial condition
[t,y] = ode45(@eom,[0,30],y0);

figure
plot(t,y(:,1)) % This plots only x(t)
% It is OK to plot both x(t) and v(t)

%[5 POINTS]

    function dVdt = growthrate(t,V)
%        Growth rate function for Gompertz equation
         dVdt = -(V/tau)*log(V/V0);
    end

    function dydt = eom(t,y)
%        equation of motion for spring-mass system
%        The vector y contains [x;v]
%        The vector dydt contains [dx/dt; dv/dt]
        dydt = [y(2);-lambda/m*y(2)-k/m*y(1)+F0/m*sin(w*t)];
        
    end

end