%%Demo 2

%% Air exchange example
clear all
close all
tEnd = 300;
V = 10*15*10*1000; %[L] volume of room
k =1/60; %[dimless] inflow factor
n = 290; %number of students
Inrate = k*V*1.6; %[g/min] amount of oxygen inflow per minute
syms yy
Outflow = k*yy;
Consumption = (yy/V)*n*7,5; %[g/min]
tspan = linspace(0,tEnd,1000);
x1 = k*V*1.6;
x2 = n*7.5/V;
x3 = k;
y0 = 1.43*V; %[g] grams of oxygen in room at time t = 0

dydt = @(t,y) x1 - x2*y - x3*y;
%Rate of change = inrate - consumption - outflow;


hold on
const = -y0*(x2+x3)+x1;
f = -(const*exp(-tspan*(x2+x3))-x1)/(x2+x3);
f = 100*f*0.21/(V*1.43)
plot(tspan,f,'r')
plot(tspan,19.5*ones(size(tspan)),'b')
plot(tspan,23.5*ones(size(tspan)),'b')
axis([0 tEnd 0 25])
xlabel('Time in minutes','FontSize',14)
ylabel('Percentage oxygen','FontSize',14)

%% Newtons metod
clear all
close all


x = linspace(-5,5,1000);
f = @(x) x.^2-2;
plot(x,f(x),'LineWidth',2)
hold on
plot(x,zeros(size(x)),'k')
pause()
x0 = 3; y0 = f(x0);
scatter(x0,y0,'r','fill')
pause()
xx = linspace(0,5,100);
y2 = @(x) f(x0) + 2*x0.*(x-x0);
plot(xx,y2(xx),'r','LineWidth',2)
pause()
x1 = x0 - f(x0)/(2*x0)
y1 = f(x1)
scatter(x1,0,'g','fill')
pause()
axis([0.5 4 -1 10])
pause()
ys = 0:0.05:f(x1);
plot(x1*ones(size(ys)),ys,'k-');
pause()
y3 = @(x) f(x1) + 2*x1.*(x-x1);
plot(xx,y3(xx),'g','LineWidth',2);
x2 = x1 - f(x1)/(2*x1);
scatter(x2,0)
