Reputation:
I have to plot the signal m(t) = ASin(2pi1000t) and I am using the following Matlab code to do it.
Fm=1000;%1 kHz
Fs = 2*Fm;
t = 0:1/Fs:10; % ( that is, time will run from 0 to 10 with a sample at every 1/2000th second )
Am=1;%amplitude
m=Am*sin(2*pi*Fm*t);
figure(1)
plot(t,m)
title('Message signal')
xlabel('Time in Seconds')
ylabel('m(t)')
However, I am getting the plot as
But on the other hand, if I use the following code,
Fm=1000;%1 kHz
t=linspace(0,10,2000);
Am=1;%amplitude
m=Am*sin(2*pi*Fm*t);
figure(1)
plot(t,m)
title('Message signal')
xlabel('Time in S')
I am getting a proper sin wave. What's actually happening here? What is wrong with the first code?
Upvotes: 2
Views: 257
Reputation: 4263
Fm=1000 #%1 kHz
here is the python version
import math
import matplotlib.pyplot as plt
Fs = 2*Fm
#t = 0:1/Fs:10 #( that is, time will run from 0 to 10 with a sample at every 1/2000th second )
t=np.linspace(0,10,Fs)
Am=1 #%amplitude
m=[ Am*math.sin(2*math.pi*Fm*value) for value in t]
plt.plot(m)
plt.show()
Upvotes: 0
Reputation: 112769
The problem with the first code snippet is that the sampling period is exactly half the period of the sinusoid. Due to the specific sampling instants that you use, you always sample the signal at its nulls. That's why you get values close to 0
(they are not exactly 0
because of the numerical inaccuracy inherent to floating-point arithmetic).
In the second code snippet, since linspace
is inclusive at its end points, the sampling period is slightly different. So you don't have the same problem as above, and you do get a sinusoid. However, you have a different problem which is now made evident, namely aliasing due to insufficient sampling. Observe how the frequency of the plotted sinusoid is very different (much smaller) from what it should be.
The solution to both problems is to increase the sample rate. According to the Nyquist criterion, a sample rate at least twice the maximum signal frequency would be enough to reconstruct the original signal. But that does not mean that directly plotting the samples taken at that rate will produce a graph resembling the signal. For that you need a factor significantly greater than 2
. Also, avoid choosing the sample rate as an integer multiple of the sinusoid frequency, to prevent problems caused by the sampling process being "coupled" to the signal variations as in your first snippet.
So, in your code, try for instance Fs = 100/3*Fm
(you may need to zoom in to see the signal properly).
Upvotes: 3