import numpy as np
a = np.arange(0, 5)
a
Calculate $$ m_i = \frac{1}{2} (a_i + a_{i+1}) $$
m = np.zeros(len(a)-1)
# write with loop
a[i]
covers the elements [0, 1, 2, 3, 4]
a[i+1]
covers the elements [1, 2, 3, 4, 5]
Think about shifting the arrays:
[0 1 2 3 4]
[0 1 2 3 4]
-------------
1 3 5 7
* 0.5
=====================
0.5 1.5 2.5 3.5
Can we get these numbers by slicing?
[1 2 3 4] = a[1:]
[0 1 2 3] = a[:-1]
-----------
1 3 5 7 = a[1:] + a[:-1]
Think about these equivalences between loop and array approach:
a[i]
is like a[:-1]
a[i+1]
is like a[1:]
# write with sliced arrays (NO loops!)
Using sliced arrays is
Prefered way to work with arrays
How fast is it?
%%timeit
for i in range(len(a)-1):
m[i] = 0.5*(a[i] + a[i+1])
%%timeit
m = 0.5*(a[:-1] + a[1:])
m
Use numpy arrays to calculate for a vector $\mathbf{b}$ of length $N$
$$ y_i = \frac{1}{2}(b_{i-1} + b_{i+1}) $$and set $y_0 = y_{N-1} = 100$.
b = np.arange(11)
b
# add your solution here