5.10.1. Exercise: Indexing and slicing unidimensional arrays#

You used an accelerometer to detect a small movement. The acceleration returned by the instrument is expressed by this list, at a sampling frequency of 100 Hz.

acc = [0.01, 0.01, 0.00, 0.00, 0.02, 0.77, 0.82, 0.86, 0.81, 0.74, 0.07, 0.02]
_images/2d7233bd08900381f9c3750824768a235295a79cff36285d6a4df0ede7e01c6c.png

However, by carefully inspecting your signal, you realize that the data is late by 40 milliseconds. You want to fix this delay, but you also want to keep the same number of samples in your signal.

  • Using NumPy slicing, write a code that moves forward every data by 40 ms.

  • Fill the missing data at the end with zeros.

In summary, you want to produce the blue curve below:

_images/5c531359bc85f57318afe54f5e594ad9a06ba7ed2bb6deb2fb3c6ad79f7698ba.png

Tip

Do not forget to convert the list to an array.

Separate the problem in two separate steps. First shift the signal, then fill the rest of the signal with zeroes. It is suggested to plot the intermediary result between both steps.

Shifting the signal is equivalent to reading a certain portion of the signal, and then assign this portion to another portion of the signal.

Hide code cell content
import numpy as np
import matplotlib.pyplot as plt


# Convert acc to an array
acc = np.array(acc)

# We will plot intermediary steps, to better visualize what we do.
plt.subplot(1, 3, 1)
plt.plot(acc, "o-")
plt.title("Original signal")

# STEP 1 - Shift the signal.
#
# At 100 Hz, the sampling period is 1/100 = 0.01. Therefore, 40 ms is 4 samples.
# We need to shift the acceleration by -4 samples. In other words, we need to
# assign acc[from sample 4 to the end] to acc[from sample 0 to the end-4]
acc[:-4] = acc[4:]

# Plot the new signal
plt.subplot(1, 3, 2)
plt.plot(acc, "o-")
plt.title("Shifted signal")

# STEP 2 - Fill the rest with zeros
acc[-4:] = 0

# Let's see the result
plt.subplot(1, 3, 3)
plt.plot(acc, "o-")
plt.title("End result")

plt.tight_layout();
_images/c49e54cb09750bc255683bda0d5c5469b77955d837b4810f8f99b3370dc70233.png