Issue with generating a sine wave via linspace and colon

13 次查看(过去 30 天)
Hi Everyone, I'm having an issue with generating a sine wave using the linspace operator vs colon operator. The code is below:
%% Generate a sinusoidal wave
fc = 300e6; % center frequency
duration = 5e-3; % Total duration
fs = 10e6; % Sampling Rate
N = fs * duration; % Total number of samples
% Method 1, using linspace
t1 = linspace(0,duration,N);
% Method 2, using colon
t = 0:1/fs:duration;
% Plotting both of them
x1=sin(2*pi*fc*t1); x = sin(2*pi*fc*t);
figure;
subplot(211)
plot(t1,x1)
subplot(212)
plot(t,x)
Running this Code gives a very different result for the colon operator as can be seen clearly. Obviously I can just use the linspace function, but the main issue I have is that I'm trying to generate the sine wave in C++, and in there there's no linspace equivalent, and I'm using getting the same output as shown in the 2nd image. Hence I'm trying to debug this issue in MATLAB first.
From what I can tell, the two time variables are mostly identical, but differ in maybe 5th-6th decimal place, which shouldn't be enough to cause such massive discrepency. If anyone can help that'd be appreciated.
  1 个评论
Dyuman Joshi
Dyuman Joshi 2023-9-12
编辑:Dyuman Joshi 2023-9-12
> "From what I can tell, the two time variables are mostly identical"
No.
linspace(x1,x2,N) generates n points with spacing (x2-x1)/(N-1), which in your case is duration/(N-1) and the spacing for colon is 1/fs, which is equal to duration/N (from the definition of N). Different spacing means the resulting vectors will not be same/similar.
To make them identical theoretically, use N+1 points with linspace
Also, Use sinpi(x) instead of sin(pi*x) as it is more accurate - sinpi

请先登录,再进行评论。

采纳的回答

DGM
DGM 2023-9-12
编辑:DGM 2023-9-12
You're trying to draw a sine wave with a frequency 30x higher than your sampling rate. The output is nothing but aliased nonsense in both cases. If you make t1 have N-1 samples, you'll see that the illusory sine wave disappears. Neither output is good.
Make some adjustments:
% Generate a sinusoidal wave
fc = 300e6; % center frequency
duration = 50e-9; % Total duration (short enough to be viewable)
fs = 10e9; % Sampling Rate (high enough to produce meaningful output)
N = fs * duration; % Total number of samples
% Method 1, using linspace
t1 = linspace(0,duration,N);
% Method 2, using colon
t2 = 0:1/fs:duration;
% Plotting both of them
x1 = sin(2*pi*fc*t1);
x2 = sin(2*pi*fc*t2);
subplot(211)
plot(t1,x1)
subplot(212)
plot(t2,x2)
  3 个评论
DGM
DGM 2023-9-12
That too, yes. I wasn't really paying attention to the difference in vector length, but if you want equivalence ...

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

标签

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by