I need to create this sine wave in MATLAB. How does one go about it?
I was given the original sine wave(Image 1) and a noisy version of it too(Image 2).
Now to find the original signal, I am looking at the frequency in the first half of the graph which has the greatest value. This would be 21. When I try to create a sine wave with 21 as a frequency using the code below, I get the result of Image 3.
% Creating the Sine Wave t = (1:1:256); A = 1; y = A*sin(2*pi*max_index*t); plot(t,y);
Why is this the case. What am I doing wrong?
Here is my Function:
function [ ] = function1b( Sig_noise ) % Max Index is the frequency of the pure tone noise_f = fft(Sig_noise); s_nf = size(noise_f); size_f = s_nf(2); max = 0; max_index = 1; for n = 1:(size_f/2) if abs(noise_f(n)) > max max = abs(noise_f(n)); max_index = n; end end % Creating the Sine Wave t = (1:1:256); A = 1; y = A*sin(2*pi*max_index*t); plot(t,y); end
And I am calling it from this part of the script:
load('Sig'); % Original Signal Sig_noise2=awgn(Sig,10); function1b(Sig_noise2);
This is the result I seem to be getting:
Using linspace(0,2,100); gives me this result:
Your code says
t = (1:1:256); A = 1; y = A*sin(2*pi*max_index*t);
While your amplitude is nice and big and 1, if max_index is integer then your phase inside the sin is an integer multiple of 2*pi for every t, which is exactly zero. This is why your function is numerically zero. You need the frequency of the max index:
y = A*sin(2*pi*freq(max_index)*t);
if the frequencies are stored in freq, or if max_index already stands for a frequency, then use a denser t mesh, like
t = linspace(1,256,1000);
You might be misinterpreting the output of fft. From help fft:
For length N input vector x, the DFT is a length N vector X, with elements N X(k) = sum x(n)*exp(-j*2*pi*(k-1)*(n-1)/N), 1 <= k <= N. n=1 The inverse DFT (computed by IFFT) is given by N x(n) = (1/N) sum X(k)*exp( j*2*pi*(k-1)*(n-1)/N), 1 <= n <= N. k=1
That means that the frequencies are not max_index, but (max_index-1)/N if your original sample has N points. This turns your flawed large frequency into the actual small frequency, solving your issues.
To break it down to you: try
t = 1:256; y = A*sin(2*pi*(max_index-1)/length(Sig_noise)*t);
I guess there is some problem in sampling rate. replace
t = (1:1/(f*3):3)
Here f=max_index =21