% Unit 3 (MATLAB Course @ UAM)
% (c) Alexander Knebe

%============================================
% Example for Unit 3
%============================================

clear all
close all
clc
format long

% EXERCISE #1:
%-------------
%
% find the circle crossing the points
%
% (3,-1)
% (-2,4)
% (6,8)
%
% equation for a cirlce
% 1. 0   = x^2 + y^2 + Ax + By + C
% 2. R^2 = (x-x0)^2 + (y-y0)^2
%
% to determine A, B, and C we need to solve the linear system
%   0 = C -1B +3A + 3^2 + 1^2
%   0 = C +4B -2A + 2^2 + 4^2
%   0 = C +8B +6A + 6^2 + 8^2

M  = [1 -1 3; 1 4 -2; 1 8 6];
b  = [-10;-20;-100];

x  = inv(M)*b;

C = (x(1))
B = (x(2))
A = (x(3))


% determine the centre and radius using the 2. equation for a circle leading to 
% (A/2)^2 + (B/2)^2 - C = (x-x0)^2 + (y-y0)^2
x0 = -A/2
y0 = -B/2
R  = sqrt(x0^2+y0^2-C)


% EXERCISE #2:
%-------------
% plot the circle using the two roots for y=f(x)
% y = y0 +- sqrt((x-x0)^2-R^2)
y1 = @(x)(y0 + sqrt(R^2-(x-x0).^2));
y2 = @(x)(y0 - sqrt(R^2-(x-x0).^2));

x = linspace(x0-R+eps,x0+R-eps,100);
plot(x,y1(x),x,y2(x),x0,y0,'x','MarkerSize',10), hold on
plot([3 -2 6],[-1 4 8],'gx','MarkerSize',10)
axis equal


% EXERCISE #3:
%-------------
% find the crossing point with y=exp(x/4)
plot(x,exp(-x./4))

f   = @(x)(y2(x) - exp(-x./4));
xr1 = bisec(f, -2.0, 0.0)

f = @(x)(y2(x) - exp(-x./4));
xr2 = bisec(f, 6.0, 8.0)

plot([xr1 xr2],[y2(xr1) y2(xr2)],'ko')

% add some labels etc.
xlim([x0-2.0*R x0+1.2*R])
ylim([y0-1.2*R y0+2.0*R])
xlabel('x')
ylabel('y')
legend('upper circle','lower circle','centre','fix points','exp(-x/4)','crossing points','Location','NorthWest')
