Finding where two lines intersect is a pretty common task in computing.
Suppose we've got \( y_1 = 2x + 3 \) and \( y_2 = -2x - 2 \).
If we want to know where these two lines intersect, it becomes a question of where is \(y_1 = y_2\).
We just set \(y1\) equal to \(y2\),
\[ 2x + 3 = -2x - 2 \,,\]and solve for \(x\).
After some algebra, we find that \(x = -\frac{5}{4}\).
using Plots
x = range(-5, 5, length=1000)
M = [ 2 ; -2 ]
B = [ 3 ; -2 ]
L1(x) = M[1]*x + B[1]
L2(x) = M[2]*x + B[2]
plot(x, L1.(x))
plot!(x, L2.(x))
From the graph, we can clearly see that \(-5/4\) is the right answer.
To solve this programmatically we put the lines into standard form,
\[\begin{aligned} -2x + y &= 3 \\ 2x + y &= -2\,, \end{aligned}\]which we put into matrix form.
\[\begin{bmatrix}-2 & 1 \\ 2 & 1 \end{bmatrix}\begin{bmatrix}x_1 \\ x_2 \end{bmatrix} = \begin{bmatrix}3 \\ -2\end{bmatrix}\]using LinearAlgebra, RowEchelon
A = [ -2 1 ; 2 1 ]
b = [3 ; -2 ]
(x1, x2) = rref([ A b ])[:, 3]
@show x1, x2
> (x1, x2) = (-1.25, 0.5)
Or by \(A^{-1}\mathbf{b}\),
A = [ -2 1 ; 2 1 ]
b = [3 ; -2 ]
(x1, x2) = inv(A)*b
@show x1, x2
> (x1, x2) = (-1.25, 0.5)
If we don't have access to easy row reduction or can't generate the inverse of a matrix easily (which is actually really easy for \(\mathbb{R}^2\) any way you cut it), the next best option is for us to use Cramer's Rule.
using LinearAlgebra
x1 = det([ b A[:, 2] ]) / det(A)
x2 = det([ A[:, 1] b ]) / det(A)
@show x1, x2
> (x1, x2) = (-1.25, 0.5)
And this is equivalent to,
(a1, a2) = A[:, 1]
(b1, b2) = A[:, 2]
(c1, c2) = b
d = a1*b2 - a2*b1
x1 = (c1*b2 - b1*c2)/d
x2 = (a1*c2 - c1*a2)/d
@show a1, a2
> (a1, a2) = (-2, 2)
@show b1, b2
> (b1, b2) = (1, 1)
@show c1, c2
> (c1, c2) = (3, -2)
@show x1, x2
> (x1, x2) = (-1.25, 0.5)