N = 1e3;
x = linspace(0, 10, N);
y = 2.0 * x - 5.0 + 3.0 * randn(1, N);
figure(1);
scatter(x, y);
hold on;
th = polyfit(x, y, 1);
yp = th(1) * x + th(2);
th
scatter(x, y);
hold on;
plot(x, yp, 'LineWidth', 7);
% pick two points at random
x1 = x(345);
x2 = x(401);
y1 = y(345);
y2 = y(401);
%%latex
Solve
\[ m x_1 + b = y_1 \]
\[ m x_2 + b = y_2 \]
for $m$ and $b$, by forming the matrix equation
\[
\begin{bmatrix}
1 & x_1 \\
1 & x_2
\end{bmatrix} \begin{bmatrix}
b \\
m
\end{bmatrix} = \begin{bmatrix}
y_1 \\
y_2
\end{bmatrix} \]
A = [1, x1;
1, x2];
c = [y1;
y2];
% A th = c
th = A \ c;
m = th(2)
b = th(1)
figure();
scatter(x, y);
hold on;
plot(x, m * x + b, 'LineWidth', 7);
hold on;
plot(x1, y1, 'MarkerSize', 40, 'Color', 'black');
plot(x2, y2, 'MarkerSize', 40, 'Color', 'black');
text(0.1, 25, 'Passes through two points, but is not a good data approximation', 'FontSize', 18);
%%latex
Solve the same equation for all values of $x_i$ and $y_i$
\[
\begin{bmatrix}
1 & x_1 \\
1 & x_2 \\
1 & x_3 \\
\vdots \\
1 & x_{n - 1} \\
1 & x_n
\end{bmatrix} \begin{bmatrix}
b \\
m
\end{bmatrix} = \begin{bmatrix}
y_1 \\
y_2 \\
y_3 \\
\vdots \\
y_{n - 1} \\
y_n
\end{bmatrix}
\]
A = [ones(length(x), 1), x(:)];
c = zeros(length(x), 1);
% do x(:) to make sure vector is vertical
% A th = c
th = A \ y(:)
b = th(1)
m = th(2)
figure()
scatter(x, y);
hold on;
plot(x, m * x + b, 'LineWidth', 7);
N = 1e3;
x = linspace(-1, 3, N);
p = [0.5, -2.0, -3.0];
y = p(1) * x.^2 + p(2) * x + p(3) + 0.5 * randn(1, N);
figure();
scatter(x, y);
Try solving
$\begin{bmatrix} 1 & x_1 & x_1^2 \\ 1 & x_2 & x_2^2 \\ 1 & x_3 & x_3^2 \\ \vdots \\ 1 & x_n & x_n^2 \end{bmatrix} \begin{bmatrix} p(3) \\ p(2) \\ p(1) \end{bmatrix} = \begin{bmatrix} y_1 \\ y_2 \\ y_3 \\ \vdots \\ y_n \end{bmatrix}$
A = [ones(length(x), 1), x(:), x(:).^2];
th = A \ y(:)
yp = A * th;
figure();
scatter(x, y);
hold on;
plot(x, yp, 'LineWidth', 7);
$f(x) = c \sin(x) + d$
c = 0.1;
d = 2.0;
N = 1e3;
x = linspace(0, 10, N);
y = c * sin(x) + d + 0.1 * rand(1, N);
figure();
scatter(x, y);
Try solving
$\begin{bmatrix} 1 & sin(x_1) \\ 1 & sin(x_2) \\ 1 & sin(x_3) \\ \vdots & \vdots \\ 1 & sin(x_n) \\ \end{bmatrix} \begin{bmatrix} \theta_1 \\ \theta_2 \\ \end{bmatrix} = \begin{bmatrix} y_1 \\ y_2 \\ y_3 \\ \vdots \\ y_n \\ \end{bmatrix}$
A = [ones(length(x), 1), sin(x(:)), x(:).^2];
% A th = y
th = A \ y(:)
figure();
scatter(x, y);
hold on;
xn = linspace(-2, 12, 100);
An = [ones(length(xn), 1), sin(xn(:)), xn(:).^2];
yn = An * th;
plot(xn, yn, 'LineWidth', 7);