Using the code below I am able to create a sign wave
JavaScript
x
28
28
1
def normalizedAmp(signalX, hz):
2
'''extract correctly-normalized amplitude'''
3
signalAmp = np.abs(signalX[0:len(hz)])
4
signalAmp[1:] = 2*signalAmp[1:]
5
return signalAmp
6
7
def sinWav(amp, freq, time, phase=0):
8
return amp * np.sin(2 * np.pi * (freq * time - phase))
9
10
# simulation parameters
11
srate = 1000
12
time = {
13
0: np.arange(0, 4, 1/srate),
14
1: np.arange(4, 8, 1/srate),
15
2: np.arange(8, 12, 1/srate)
16
}
17
18
signal = sinWav(amp=0.25, freq=2, time=time[0])
19
20
plt.figure(figsize=(12,3))
21
22
# plot time-domain signal
23
plt.subplot2grid((1,3), (0,0))
24
plt.plot(time[0], signal)
25
plt.xlabel('Time (ms)')
26
plt.ylabel('Amplitude')
27
plt.title('Time domain')
28
I would like to create a sin wave which changes it’s amplitude at time 4s, and 8s so that the sin wave looks like the image below
I know how to create each of the 3 sin waves in that img, but I don’t know how to combine them into one.
I’ve tried to combine the first two by doing
JavaScript
1
2
1
np.concatenate(sinWav(amp=0.25, freq=2, time=time[0]), sinWav(amp=1, freq=2, time=time[0]))
2
and receive the error
JavaScript
1
2
1
ValueError: x and y must have same first dimension, but have shapes (4000,) and (8000,)
2
Advertisement
Answer
You can concatenate arrays by making a list of them as parameter to np.concatenate
(e.g. np.concatenate([array1,array2,array3])
or as tuple: np.concatenate((array1,array2,array3))
) :
JavaScript
1
27
27
1
import matplotlib.pyplot as plt
2
import numpy as np
3
4
def sinWav(amp, freq, time, phase=0):
5
return amp * np.sin(2 * np.pi * (freq * time - phase))
6
7
# simulation parameters
8
srate = 1000
9
time = {0: np.arange(0, 4, 1 / srate),
10
1: np.arange(4, 8, 1 / srate),
11
2: np.arange(8, 12, 1 / srate)}
12
13
signal = sinWav(amp=0.25, freq=2, time=time[0])
14
15
plt.figure(figsize=(12, 3))
16
17
# plot time-domain signal
18
plt.plot(np.concatenate([time[0], time[1], time[2]]),
19
np.concatenate([sinWav(amp=0.25, freq=2, time=time[0]),
20
sinWav(amp=1.0, freq=2, time=time[1]),
21
sinWav(amp=0.5, freq=2, time=time[2])]))
22
plt.xlabel('Time (ms)')
23
plt.ylabel('Amplitude')
24
plt.title('Time domain')
25
plt.tight_layout()
26
plt.show()
27