Week 1.3: Programming Tutorial¶
CEGM1000 MUDE: Week 1.3. September 16, 2024.
This notebook was prepared by Berend Bouvy and used in an in-class demonstration on Monday (the first of several programming tutorials).
In [74]:
def add(a, b):
result = a+b
return result
def gen_xhat(A, y):
x_hat = np.linalg.inv(A.T @ A) @ A.T @ y
return x_hat
In [6]:
a = 1
b = 2
result = add(a, b)
result
Out[6]:
3
In [25]:
import numpy as np
import matplotlib.pyplot as plt
In [11]:
# Replace 'file.csv' with the path to your CSV file
data = np.genfromtxt('data.csv', delimiter=',', skip_header=1) # 'skip_header=1' skips the first row (header)
(100, 2)
In [37]:
t = data[:,0]
y = data[:,1]
n_rows = data.shape[0]
n_cols = data.shape[1]
In [61]:
plt.plot(t, y,'o')
plt.title('t vs y')
plt.xlabel('t')
plt.ylabel('y')
Out[61]:
Text(0, 0.5, 'y')
In [39]:
one_vector = np.ones(n_rows)
In [42]:
print(one_vector+ t)
[ 1. 1.1010101 1.2020202 1.3030303 1.4040404 1.50505051 1.60606061 1.70707071 1.80808081 1.90909091 2.01010101 2.11111111 2.21212121 2.31313131 2.41414141 2.51515152 2.61616162 2.71717172 2.81818182 2.91919192 3.02020202 3.12121212 3.22222222 3.32323232 3.42424242 3.52525253 3.62626263 3.72727273 3.82828283 3.92929293 4.03030303 4.13131313 4.23232323 4.33333333 4.43434343 4.53535354 4.63636364 4.73737374 4.83838384 4.93939394 5.04040404 5.14141414 5.24242424 5.34343434 5.44444444 5.54545455 5.64646465 5.74747475 5.84848485 5.94949495 6.05050505 6.15151515 6.25252525 6.35353535 6.45454545 6.55555556 6.65656566 6.75757576 6.85858586 6.95959596 7.06060606 7.16161616 7.26262626 7.36363636 7.46464646 7.56565657 7.66666667 7.76767677 7.86868687 7.96969697 8.07070707 8.17171717 8.27272727 8.37373737 8.47474747 8.57575758 8.67676768 8.77777778 8.87878788 8.97979798 9.08080808 9.18181818 9.28282828 9.38383838 9.48484848 9.58585859 9.68686869 9.78787879 9.88888889 9.98989899 10.09090909 10.19191919 10.29292929 10.39393939 10.49494949 10.5959596 10.6969697 10.7979798 10.8989899 11. ]
In [79]:
A = np.column_stack((one_vector, t))
In [75]:
x_hat = gen_xhat(A, y)
y_hat = A @ x_hat
In [76]:
plt.plot(t, y,'o')
plt.plot(t, y_hat)
plt.title('t vs y')
plt.xlabel('t')
plt.ylabel('y')
Out[76]:
Text(0, 0.5, 'y')
In [77]:
A_new = np.column_stack((one_vector, t, t**2))
x_hat_new = gen_xhat(A_new, y)
y_hat_new = A_new @ x_hat_new
plt.plot(t, y,'o')
plt.plot(t, y_hat_new)
plt.title('t vs y')
plt.xlabel('t')
plt.ylabel('y')
Out[77]:
Text(0, 0.5, 'y')
In [73]:
e_hat = y-y_hat_new